gpt4 book ai didi

C. 打印出来的不对,目前还没搞清楚原因

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:08 25 4
gpt4 key购买 nike

这是我的代码:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void splitString(char s[]) {

char firstHalf[100] = { 0 };
char secndHalf[100] = { 0 };

for (int i = 0; i < strlen(s) / 2; i++){
firstHalf[i] = s[i];
}

for (int i = strlen(s) /2; i < strlen(s); i++){
secndHalf[i - strlen(s) / 2] = s[i];
}

printf("The string split in two is '%s, - %s' \n", firstHalf, secndHalf);
}

void upperCase(char s[]){

//String in upper case
for (size_t i = 0; i < strlen(s); i++)
s[i] = toupper(s[i]);

printf("The string in uppercase is '%s'", s);
}

void lowerCase(char s[]){

//String in lower case
for (size_t i = 0; i < strlen(s); i++)
s[i] = tolower(s[i]);

printf("The string in lowercase is '%s'", s);
}

int main() {

char s[200];
char splitS[200];

printf("Type a string: ", sizeof( s));

if (fgets(s, sizeof(s), stdin) != 0){
printf("The string is '%s'", s);
}

strcpy(splitS, s);

upperCase(s);
lowerCase(s);
splitString(splitS);

return 0;
}

正确的打印方式应该是这样的:

The string is 'Hello world'

The string in uppercase is 'HELLO WORLD'

The string in lowercase is 'hello world'

The string split in two is 'Hello, - world'

但是它打印成这样:

The string is 'Hello world

'The string in uppercase is 'HELLO WORLD

'The string in lowercase is 'hello world

'The string split in two is 'Hello , - world

'

最佳答案

您需要阅读 documentation for fgets() (我的重点):

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.

由于您输入的这些行末尾有换行符,因此您需要在代码中删除它们。

关于C. 打印出来的不对,目前还没搞清楚原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40128214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com