Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 福卢斯替代方案_C_String_Generics - Fatal编程技术网

C 福卢斯替代方案

C 福卢斯替代方案,c,string,generics,C,String,Generics,我犯了这样一个错误:使用fflush(stdin)刷新stdin流的剩余内容: printf("Gimme number"); scanf("%d",&number); fflush(stdin); printf("Gimme string"); gets(string); 当然,我已经包括了头文件和其他文件。。我知道fflush是用于stdout而不是stdin的,但是为了在scanf之后使用get,我迫切需要一个替代方法。我在这里搜索了一些旧帖子,但只看到了一条关于scanf的建议

我犯了这样一个错误:使用fflush(stdin)刷新stdin流的剩余内容:

printf("Gimme number");
scanf("%d",&number);
fflush(stdin);
printf("Gimme string");
gets(string);

当然,我已经包括了头文件和其他文件。。我知道fflush是用于stdout而不是stdin的,但是为了在scanf之后使用get,我迫切需要一个替代方法。我在这里搜索了一些旧帖子,但只看到了一条关于scanf的建议(“%c\n”,c)。当我执行scanf(“%d\n”,x)时,这会导致程序崩溃;有什么想法吗?

一种可能是使用
scanf
留下的换行符,例如
getchar()

另一种可能是使用scanf的:

printf("Gimme number");
scanf("%d",&number);
printf("Gimme string");
scanf(" %99s", string);

如果要将
99
替换为字符串缓冲区的长度,请注意
%
之前的空格,以确保它忽略
stdin

上留下的空白(或制表符或换行符),从输入中读取完整的行(包含ENTER的行)。 解析行(可能使用
strtol()
srttod()
,或
sscanf()


尝试
scanf(“%d”,数字)(是,包括空格)。不要使用
gets
,尝试
fgets
旋转。甚至
scanf(“%d”和&number)?切勿使用
get()
。它本质上是不安全的,以至于它已经从最新版本的C标准中删除了(这是唯一一个遭受这种命运的函数)???如果我不知道用户将键入多少字符,以便输入大小,该怎么办?我确实在代码中输入了&number!!这是个打字错误。。对不起@alex777-NP,更新了我的代码以匹配。感谢您指出这一点。
%s
转换本身跳过前导空格,您不需要空格。除非规范包含[、c或n说明符,否则将跳过输入空格字符(由isspace函数指定)
printf("Gimme number");
scanf("%d",&number);
printf("Gimme string");
scanf(" %99s", string);
char buffer[1000];
int number;
printf("Gimme number: ");
fflush(stdout);
fgets(buffer, sizeof buffer, stdin); // needs error checking
number = strtol(buffer, &err, 10); // needs error checking
printf("Gimme string: ");
fflush(stdout);
fgets(buffer, sizeof buffer, stdin); // needs error checking
strcpy(string, buffer);
string[strlen(string) - 1] = 0; // remove ENTER