我正在尝试使用以下输入的 C 程序。
6
7.0
How are you
我能够读取和打印整数和 double 据类型变量,但字符串变量不接受用户的任何输入并自行打印整数变量值
int
的代码:
int j;
double e;
char str[100];
printf("enter the integer variable :");
scanf("%d", &j);
printf("enter the double variable :");
scanf("%lf", &e);
printf("enter the string :");
scanf("%[^\n]s",str);
printf("integer variable is %d\n",j);
printf("float variable is %0.1f\n",e);
printf("string variable is %s\n", str);
输出:
enter the integer :3
enter the double :4.0
enter the string :integer variable is 3 -> (automatically accepting printf of integer case and exiting the code)
float variable is 4.0
string variable is ??LX?
但是如果我首先读取字符串值(在读取整数和 double 值之前),那么代码就可以正常工作。
字符串
的代码:
printf("enter the string :");
scanf("%[^\n]s",str);
printf("enter the integer variable :");
scanf("%d", &j);
printf("enter the double variable :");
scanf("%lf", &e);
printf("integer variable id %d\n",j);
printf("float variable is %0.1f\n",e);
printf("string variable is %s\n", str);
输出:
enter the string :how are you
enter the integer :6
enter the double :7.0
integer variable is 3
float variable is 4.0
string variable is how are you
最佳答案
scanf()
中的转换格式前加一个空格:
scanf(" %99[^\n]", str); // skip whitespace and read up to 99 characters on a line
这将指示 scanf()
跳过 stdin
中待处理的换行符缓冲区,以及下一行中的任何前导空格。事实上,它会继续读取行,直到用户键入非空行或到达文件末尾。您应该测试 scanf()
的返回值验证是否 scanf()
成功了。
此外,你必须告诉scanf()
存储到 str
的最大字符数否则,足够长的输入行将导致缓冲区溢出,并带来可怕的后果,因为这可能构成可利用的缺陷。
另请注意,解析扫描集的语法为 %99[^\n]
:无尾随 s
是必需的。
关于c - 读取 double 据类型后无法读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40853105/