读取文件的功能不起作用。互动菜单问题

帕特里克(Patryk Piwowarczyk)

我在使新开始的项目正常工作时遇到了一些问题(也是我的初学者)。由于某种原因,我的交互式菜单中的第4个选项不起作用,仅采用默认路由(不输出文件内部内容(文件目录就可以)。)。

至此,我已经阅读了每个论坛的答案,但无法以任何可行的方式修改我的代码。因此,我决定向您寻求帮助。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#define kFileLocation "/Users/patrykpiwowarczyk/Desktop/STUDIA/FoCP/Kodowanie/TestProjektSemestralnyAngielski/TestProjektSemestralnyAngielski/authors.txt"

void options();
void start(void);
void score(void);
void optionz(void);
void author(void);

void pexit(void);

    int main(void)
    {
        char ch;
        int num;
        char option;
        while (1) {
            printf("****Your English Learning Index Cards****\n\n");
            printf("Enter 1-5 of the following options: \n\n");
            options();
            scanf("%c", &option);

            switch (option) {
                case '1':

                    break;
                case '2':

                    break;
                case '3':
                    break;
                case '4':
                    author();
                    break;
                case '5':
                    pexit();
                    break;
                default:
                    printf("Please insert number ranging from 1-5 though... No cheating! \n\n");
                    printf("Press ENTER key to Continue\n");

            }


        }
        return 0;
    }

    void options()
    {
        printf("1. Start Game \n");
        printf("2. View Scoreboard \n");
        printf("3. Options \n");
        printf("4. Author \n");
        printf("5. Exit \n\n");
    }

void author()
{

    char c;
    FILE *authorsFile;


    if ((authorsFile = fopen("/Users/patrykpiwowarczyk/Desktop/STUDIA/FoCP/Kodowanie/TestProjektSemestralnyAngielski/TestProjektSemestralnyAngielski/authors.txt","r")) == NULL)
    {
        printf("FAILED to read the file, maybe check directory?\n");
        exit(1);
    }

    while ((c = fgetc(authorsFile)) != EOF)
    {

        printf("%c", c);
    }

    fclose(authorsFile);


}

void pexit()
{

    puts("Your progress has been saved, see you next time.");
    exit(0);
}

如果您能以任何方式帮助我,我将非常感谢。

问候,Patryk Piwowarczyk。

PS:#define kFileLocation是我其他尝试的剩余内容。不用了

安德烈亚斯·温泽尔(Andreas Wenzel)

根据您的评论,我得出以下结论:

问题在于,首次调用scanf数字时,已正确将数字写入变量中option但是,第二次scanf被调用时,它立即从上一个菜单选择中返回换行符,而不是等待用户输入其他数字。每当scanf返回换行符时,都会触发默认情况。

因此,可以通过将scanf调用更改为以下内容来最好地解决该问题

scanf(" %c", &option);

通过在格式字符串的开头添加一个空格,您可以指示scanf在读取字符之前放弃所有空白字符。这样,您可以确保换行符永远不会写入option变量。

scanf这个问题中已经详细讨论读取换行符而不是丢弃它们的问题

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章