【问题标题】:scanf and switch statement debugscanf 和 switch 语句调试
【发布时间】: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", &amp;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", &amp;input); 1) 只调用一次printf(),每个字符串用空格分隔。 2) 'wrapped' 字符串将无法编译。对 scanf() 格式字符串的调用需要一个前导空格来消耗任何剩余的 '\n' 等
  • OT:switch() 语句需要 default 大小写,以便用户未输入 4 个预期字符之一。

标签: c algorithm switch-statement scanf


【解决方案1】:

char name;name 只能包含一个字符。因此,例如,当您键入:cuqname 将包含c,然后insertname 执行任何操作,然后返回到main。然后在mainscanf("%c", &amp;input) 将从输入缓冲区('u' 和'q')中读取剩余的字符,并且由于case 'q': 程序停止。使用调试器或将一些 printfs 放在代码中的关键位置,看看会发生什么。

你想要一个字符串,你可能想要在insert中这样的东西:

char name[100];
printf("enter your name: ");
scanf("%s", name);
...

您可能还需要更改Thesame 函数。

【讨论】:

  • 为避免可能的缓冲区溢出,请将:scanf("%s", &amp;name); 替换为:scanf("%99s", name); 注意:对数组的裸引用会降级为数组第一个字节的地址,因此不要使用数组名称上的&amp;
猜你喜欢
  • 2016-03-02
  • 2019-04-07
  • 1970-01-01
  • 2011-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多