我今年夏天刚刚开始操作系统类(class),我们需要用 C 语言进行编程。
我只用 C++ 编写过代码,所以我对 C 是全新的。我们的第一个作业是输入多个字符串的简单提示。我们最多只能读入 10 个字符串。
我的问题是 scanf()
没有在循环中等待用户输入,程序只显示提示 10 次,然后我才有机会输入任何内容。我读到这是因为 scanf()
在缓冲区中有换行符,所以我在 scanf()
中的 %c
之前添加了一个额外的空格> 按照建议的声明,但这并没有解决问题。
#include <stdio.h>
int main (void)
{
int SIZE = 10;
char* states[SIZE];
int cnt = 0;
printf ("Here\n");
while (cnt < 10)
{
printf ("Enter State and Pop: ");
scanf (" %c ", &states[cnt]);
cnt++;
printf ("%d\n", cnt);
}
return 0;
}
最佳答案
char* states[SIZE]; //pointers not allocated with memory
scanf (" %c ", &states[cnt]); //wrong format specifier and argument
这是未定义的行为,因为您使用了错误的格式说明符,并且还发送了错误的参数以在字符串中扫描
以及指向字符串的指针,即
states
未分配内存
为了避免这种情况,首先为 states
数组中的每个字符串分配内存
包含
stdlib.h
头文件为
状态
中的每个指针分配内存并返回地址for(int i=0; i<10; i++) { states[i] = malloc(max_size_of_string); }
或者您可以通过这种方式非动态分配内存:
char states[10][max_size_of_strings];
<小时/>
最后这样使用 scanf :
scanf (" %(size_of_string-1)[^\n]", states[cnt]);
即,如果您将 max_size_of_string 指定为 10,则使用以下方式:
scanf (" %9[^\n]", states[cnt]);
这是为了避免覆盖终止空字符
关于c - scanf 不在 while 循环中等待用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38363808/