【发布时间】:2020-10-07 16:57:45
【问题描述】:
除了 switch 'a' case 之外的所有情况都有效。 a case 运行下面的 insert 方法。任何帮助将不胜感激,谢谢。 switch 语句中的 printf 语句不起作用。
void insert() {
char name;
printf("enter your name");
scanf("%c", &name);
for(int i = 0; i < LENGTH; i++){
if (!Thesame(names[1], name) == 0 && counter != LENGTH && strlen(name) <= MAX){
for(int j = 0; j < LENGTH; j++){
strcpy(names[counter],name);
}
}
else{
printf("error");
}
}
```
int main() {
while (1) {
char input;
printf("Type in 'a' be added to the system \n");
printf("Type in 'n' to print next patient and remove from
waitlist \n");
printf("Type in 'l' to list the patients on the waitlist \n");
printf("Type in 'q' to quit the program \n");
scanf("%c", &input);
switch (input) {
case 'a':
insert();
break;
case 'n':
next();
break;
case 'l':
print();
break;
case 'q':
return 0;
}
}
}
【问题讨论】:
-
您自己调试此问题的一种非常简单的方法是添加打印以查看哪里出了问题。在插入函数中打印以查看它是否进入所有 if 条件将帮助您找到问题所在,然后您可以询问/搜索更具体的问题。
-
如果您在响应
char name; printf("enter your name"); scanf("%c", &name);时输入了一个字符串,除了第一个字符之外的所有字符都将保留在输入缓冲区中以供其他地方使用。你不能像编译器告诉你的那样应用strlen(name)。 -
关于:
printf("error");。始终以'\n'结束格式字符串,因此数据会立即输出到终端。否则,数据将位于stdout流缓冲区中,直到发生一些“触发”,例如缓冲区溢出或输出“\n”或执行输入语句或程序结束 -
关于;
printf("Type in 'a' be added to the system \n"); printf("Type in 'n' to print next patient and remove from waitlist \n"); printf("Type in 'l' to list the patients on the waitlist \n"); printf("Type in 'q' to quit the program \n"); scanf("%c", &input);1) 只调用一次printf(),每个字符串用空格分隔。 2) 'wrapped' 字符串将无法编译。对scanf()格式字符串的调用需要一个前导空格来消耗任何剩余的 '\n' 等 -
OT:
switch()语句需要default大小写,以便用户未输入 4 个预期字符之一。
标签: c algorithm switch-statement scanf