c - 读取 double 据类型后无法读取字符串

标签 c

我正在尝试使用以下输入的 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/

相关文章:

c - 错误 : unknown type name 'CURL'

c - 在C中获取鼠标点击的坐标

c - 使用 fork() 的多个进程

条件编译 - 实现替代方案

c - 如何检查该函数在编译器上是否可用?

c - Opencv cvSetImageROI坐标问题

c++ - NDEBUG 预处理器宏用于(在不同平台上)是什么?

c - 共享内存中的指针 - C 语言 Linux

c - STDIN_FILENO 和 STDOUT_FILENO 在 c 中只读吗?

C 循环中的 char 数组赋值?