代码不允许我输入并立即结束

标签 c arrays string clion sentence

我创建了一个函数来反转句子中的所有单词,这意味着如果输入是“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/

相关文章:

c - 'const struct' 与 'struct' 有何不同?

c - 宏数组访问的语法错误

c++ - 尝试使用 MSMXL 在 C++ 中使用 pXMLDom 加载字符串

ruby-on-rails - 字符串:用 * 号屏蔽最后 n 个字符

c - 我怎样才能将二进制转换为c中的字符串

c - 在C中对字符串数组进行排序

c - 如何将 exec 输出存储到文件中?

C++ 指针目标返回错误值

java - java中比较数组字符串以获得 boolean 值

c - 一道新手C题