【问题标题】:'for' loop seems to be looping though twice“for”循环似乎循环了两次
【发布时间】:2021-01-26 07:03:02
【问题描述】:

我正在编写一个程序,在 C 中对文本文件执行简单的输入/输出操作。假设向用户显示几个选项,然后执行选定的操作并重新显示所述选项。我遇到的问题是我正在使用的 for 循环似乎循环了两次,因此显示的选项是两次。我不确定我做错了什么,任何帮助将不胜感激。

代码如下:

for (;;) {
    printf("\nPlease choose from the fellowing options: \n\n");
    printf("Press (S) to sreach for a word\n");
    printf("Press (L) to display specified number of text lines to the screen\n");
    printf("Press (A) to append new content to the file\n");
    printf("Press (Q) to quit\n\n");
    printf("Please enter option: ");
    option = getchar();

    if (option == 'S' || option == 's') {
        //Search for a word in file.
        printf("Test\n");           
    }
    else if (option == 'L' || option == 'l') {
        //Display number of line specified by user.
        printf("Test\n");           
    }
    else if (option == 'A' || option == 'a') {
        //Append new content into file.
        printf("Test\n");           
    }
    else if (option == 'Q' || option == 'q') {
        //Quit program.
        exit(EXIT_SUCCESS);
    }
    else {
        printf("Invalid input!\n");
    }       
}

这是输出:

请从奖学金选项中选择:

按 (S) 搜索单词 按 (L) 在屏幕上显示指定数量的文本行 按 (A) 将新内容附加到文件中 按 (Q) 退出

请输入选项:s 测试

请从奖学金选项中选择:

按 (S) 搜索单词 按 (L) 在屏幕上显示指定数量的文本行 按 (A) 将新内容附加到文件中 按 (Q) 退出

请输入选项:输入无效!

请从奖学金选项中选择:

按 (S) 搜索单词 按 (L) 在屏幕上显示指定数量的文本行 按 (A) 将新内容附加到文件中 按 (Q) 退出

请输入选项:

【问题讨论】:

  • printf("Invalid input '%c'!\n", option); 在最后一个 else 你会弄明白的。

标签: c


【解决方案1】:

我猜问题是 getchar() 从 stdin 中读取了 1 个字符(您将输入输入到控制台) 所以它不会读取您在第一个循环中插入输入流的 endline(enter),这就是为什么当您第二次调用 getchar 时获得 Invalid input。

改用 scanf 之类的,或者甚至更好地将行读入 char* 缓冲区并在缓冲区上工作,而不是直接使用标准输入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 2016-01-09
    相关资源
    最近更新 更多