我创建了一个函数来反转句子中的所有单词,这意味着如果输入是“Hello World”,则输出应该是“World Hello”。下面的代码是函数。
char* reversesentence(char sent[]) {
int lth = strlen(sent);
int i;
for(i = lth -1; i >= 0; i--) {
if(sent[i] == ' ') {
sent[i] = '\0';
printf("%s ", &(sent[i]) + 1);
}
}
printf("%s", sent);
}
在主体中,我试图向用户询问句子并在主体中调用函数。
int main(void)
{
char sentence[2000];
printf("Please enter the sentence you want to be reversed.\n");
scanf("%s", sentence);
reversesentence(sentence);
printf("%s", sentence);
}
数组似乎只存储了句子的第一个单词。
输出:
Please enter the sentence you want to be reversed.
hello my name is
hellohello
Process finished with exit code 0`
有人可以帮我解决这个问题吗?在网上搜索,没有找到任何有用的东西。
最佳答案
scanf
在出现空格、制表符或换行符时停止读取。
Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.
因此您在输入时并没有读取整个字符串。
尝试使用 fgets
,如下所示。
fgets(sentence, sizeof(sentence), stdin);
Note
fgets
appends\n
to end of the string. see how to trim the new line from fgets
关于代码不允许我输入并立即结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54071555/