无法在字符串和指定的字符中找到 space,即使是通过简单的方法
Can't find space in string and specified char , even by simple method
我正在使用此方法在字符串中查找 space 或指定的单词。
但这种方法不起作用。我查了很多遍流量
#include <stdio.h>
int main()
{
char text[50], find;
int i = 0, sp = 0;
printf("Enter text: \n");
scanf("%s", text);
printf("Enter a char to find:\n");
scanf("%c", &find);
while ( text[i] != '[=11=]') // to receive a value untill enter is pressed.
{
if (text[i] == find) // count if text[i] is the specified value.
{ sp++; }
i++;
}
printf("%d", sp); // prints 0 always. how to fix this.
}
您不能使用scanf()
来读取带有space 的字符串。一旦遇到 space,scanf()
就会退出。
改用fgets()
。
至于在字符串中查找单词,比较字符串使用 strcmp()
。
旁注:
1) 检查 scanf()
的 return 值
2) 使用main()
的标准定义
int main(void) //if no command line arguments.
代码中的 find
始终分配有 \n
或您在扫描字符串 text
末尾输入的换行符。尝试给出 space 在 find
的 scanf
语句中:
scanf(" %c",&find)
为什么要给一个space?
通过给出一个 space,编译器从前面的 scanf
中省略 '\n'
字符
Note: scanf("%s",string)
ends scanning when it encounters white space i.e, '\n'
or '[=20=]'
or '\t'
but to account for spaces, try
using this scanf("%[^\n]s",string")
我找到了解决方案:
scanf("%[^\n]", fullName);
工作正常。并接收整行
我正在使用此方法在字符串中查找 space 或指定的单词。 但这种方法不起作用。我查了很多遍流量
#include <stdio.h>
int main()
{
char text[50], find;
int i = 0, sp = 0;
printf("Enter text: \n");
scanf("%s", text);
printf("Enter a char to find:\n");
scanf("%c", &find);
while ( text[i] != '[=11=]') // to receive a value untill enter is pressed.
{
if (text[i] == find) // count if text[i] is the specified value.
{ sp++; }
i++;
}
printf("%d", sp); // prints 0 always. how to fix this.
}
您不能使用scanf()
来读取带有space 的字符串。一旦遇到 space,scanf()
就会退出。
改用fgets()
。
至于在字符串中查找单词,比较字符串使用 strcmp()
。
旁注:
1) 检查 scanf()
2) 使用main()
int main(void) //if no command line arguments.
代码中的 find
始终分配有 \n
或您在扫描字符串 text
末尾输入的换行符。尝试给出 space 在 find
的 scanf
语句中:
scanf(" %c",&find)
为什么要给一个space?
通过给出一个 space,编译器从前面的 scanf
'\n'
字符
Note:
scanf("%s",string)
ends scanning when it encounters white space i.e,'\n'
or'[=20=]'
or'\t'
but to account for spaces, try using thisscanf("%[^\n]s",string")
我找到了解决方案:
scanf("%[^\n]", fullName);
工作正常。并接收整行