【发布时间】:2016-03-09 05:23:58
【问题描述】:
同时,每当我使用内置函数gets 和scanf 函数获取输入字符串和字符时,我都会遇到问题。
首先,每当我使用gets 获取输入字符串,然后在scanf 函数的帮助下输入一个字符时,编译器不会响应获取字符,尽管它从gets 函数获取输入并直接跳过scanf函数从用户那里获取一个字符。
查看下面的代码并将其运行到您的编译器以了解问题
#include <stdio.h>
#include <string.h>
int main()
{
int i,l,T,exit;
char str[1000];
char ch;
scanf("%d",&T);
while( (T-- ) ){
gets(str);
scanf("%c",&ch);
l = strlen(str);
exit = 0;
for( i = 0; i < l; i++ ){
if( str[i] == ch )
exit++;
}
if(!(exit))
printf("'\%c\' is not present\n",ch);
else
printf("Occurrence of '\%c\' in '\%s\' = %d\n",ch,exit);
}
return 0;
}
【问题讨论】:
-
你不应该使用
gets(),它有不可避免的缓冲区溢出风险。 -
Couldn't reproduce。
scanf()似乎运行良好。 -
它对我不起作用。如果我添加例如 printf("enter the char");或 fflush(NULL)。看起来 scanf 只是从流中获取第一个字符。正如你所指出的,应该使用gets。编译器也会发出同样的警告。我认为用 scanf 替换 OP 会更好。
-
我建议扫描字符串并使用
strchr()函数检查字符串中是否存在字符。