简体   繁体   English

在C中的scanf()函数有问题吗?

[英]Issue with scanf() function in c?

#include<stdio.h>
void main()  
 {  
  int i;  
   char a[20];   
   char b[20];   
   scanf("%d",&i);  
    gets(a);   
    puts(a);  
gets(b);  
puts(b); 

} }

Here,after entering the value of 'a' it is printing the value of i and a.It is not taking the value of 'b'.How i can insert the value of 'b'? 在这里,输入'a'的值后将打印i和a的值。它不使用'b'的值。我如何插入'b'的值?

1) Never use gets , it has been removed from the C standard, and is unsafe. 1)切勿使用gets ,它已从C标准中删除,并且是不安全的。 Use fgets instead, (eg, fgets(a, sizeof a, stdin); ). 改用fgets (例如fgets(a, sizeof a, stdin); )。 Note that fgets doesn't remove the newline from the end of the string. 请注意, fgets不会从字符串末尾删除换行符。

2) The return type of main is int , not void . 2) main的返回类型为int ,而不是void

3) The scanf does not consume the newline after reading i , so gets(a) results in a being the empty string because it reads the newline that was buffered from when the user pressed return after typing the number. 3) scanf不消耗阅读之后的换行符i ,所以gets(a)的结果在a为空字符串,因为它读取一个从缓冲当用户按压键入号码后返回的换行符。 Then gets(b) reads what you thought was a . 然后gets(b)读取您认为是a (Print some prompts before reading each value and you'll see. Or try the input: 1 a Enter b Enter ) (在读取每个值之前,请打印一些提示,您将看到。或尝试输入: 1 a Enter b Enter

Suggested solution: use fgets to read i into a buffer, then, eg, atoi or strtol to convert it to an integer. 建议的解决方案:使用fgetsi读入缓冲区,然后使用atoistrtol将其转换为整数。 (Or you could do an extra fgets after scanf , or getchar in a loop until you've read a newline, but, seriously, the fgets solution is a lot more robust and worth learning now.) (或者,您可以在scanf之后执行额外的fgets ,或者循环读取getchar ,直到您阅读换行符为止,但是,认真地讲, fgets解决方案更强大,现在值得学习。)

  gets(a);   

Don't use gets it is evil. 不使用gets是邪恶的。 Try fgets 尝试fgets

#include<stdio.h>
int main()   //declare here `int main()`
 {  
     int i;  
     char a[20],c[10];   
     char b[20];   
     fgets(c,sizeof c,stdin);
     i=atoi(c);         
     fgets(a,sizeof a,stdin);   
     puts(a);  
     fgets(b,sizeof b,stdin);  
     puts(b); 
     return 0;
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM