我正在尝试计算空格前单词的字母数。例如。 “Hello how”是我的输入字符串,我正在尝试计算第一个单词中的字母数。
#include<stdio.h>
#include<string.h>
int main()
{
char a[30];
int count = 0;
printf("Enter the string.\n"); // Enter hello how as string here.
gets(a);
for ( i = 0; a[i] != '\0'; i++ )
{
while( a[i+1] != ' ' )
count++;
}
printf("%d\n",count);
}
这是更大代码的一小部分,我实际上希望计数的值为 5,但它进入了某种我无法弄清楚的无限循环。如果我使用 if 而不是 while ,我会得到预期的答案。我知道 gets 不是很可靠,一旦我在编程方面做得更好,我就不会使用,所以你最好发布关于循环而不是 gets 的答案。谢谢。
最佳答案
NUL 字符用反斜杠 (\
) 书写,而不是正斜杠 (/
)。
for (i = 0; a[i] != '\0'; i++)
此外,内部循环不会终止,因为您没有递增 i
。
while (a[i] != ' ') {
i++;
count++;
}
实际上,你不应该真的有两个循环。您只需要一个循环。
for (i = 0; a[i] != '\0' && a[i] != ' '; i++) {
count++;
}
关于c - 这里的 while 循环有什么问题? C基础知识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21634060/