【问题标题】:C: writing/reading files using do while loopC: 使用 do while 循环写入/读取文件
【发布时间】:2018-05-11 04:51:06
【问题描述】:

我正在用 C 语言编写一个简单的练习应用程序,它应该询问用户是要写入文件还是读取文件。我想给文件命名,然后在控制台中输入一些文本。我想使用该文本将其保存到文件中。

问题是,当我已经为文件命名时,我无法将数据输入到控制台,因此我无法将这些数据保存到文本文件中。此外,while 循环会忽略我的 'y' 以再次重新启动程序。此外,当我想使用读取文件时,它确实可以,程序可以工作,但它也会添加默认指令(仅打印错误),但我不希望这样,只需从文件中读取并将其打印到控制台。

谁能解释我做错了什么以及如何解决这个问题?我将不胜感激。

这是我的代码:

int main()
{
FILE *file;
char nameFile[32];
char string[500];
char ans[2];
int choice;

do{
    printf("What do you want to do?\n");
    printf("1. Write text to file\n");
    printf("2. Read text file\n");
    scanf("%d", &choice);
    switch (choice) {
        case 1:
            printf("Give name to the file (*.txt).\n");
            scanf("%s", nameFile); //This line skips me to line where program ask user if restart the program (I have no idea why :()
            system("clear");
            file=fopen(nameFile, "w");
            if(file!=NULL){
                printf("Input text:\n");
                scanf("%[^\n]", string); //<--- HERE I'cant input text to console, seems like scanf doesn't work.
                fprintf(file, "%s", string);
                printf("\n\t\t\t-----------Ended writing.------------\n");
                fclose(file);
            }
            else
            {
                printf("Could not open the file.");
                return -1;
            }
            break;
        case 2:
            printf("Give name to the file (*.txt)");
            scanf("%s", nameFile);
            system("clear");
            file=fopen(nameFile, "r");
            if(file!=NULL){
                while (!feof(file)) {
                    fscanf(file, "%s", string);
                    printf("%s\n",string); //After printing data from text file, adds instruction from line , and that is printing Error. How to get rid of it?
                }
            }
            else{
                printf("Could not open the file.");
                return -1;
            }
        default:
            printf("Error.");
            break;
    }
    printf("Do you want to restart the program? (y/*)"); //Even if I write 'y', program ends anyway :(
    scanf("%s", ans);
}
while(ans=='y');
return 0;
}

https://ideone.com/aCYJR5

【问题讨论】:

  • 你错过了休息时间;案例 2 末尾的语句。这就是我更喜欢 if 语句的原因之一。
  • 我真的忘记了 - 谢谢,终于不再打印错误了。

标签: c input while-loop switch-statement file-writing


【解决方案1】:

scanf("%[^\n]", string); 不工作,除非输入缓冲区被清除。请改用scanf("%499s", string),其中499 是字符串的大小减1。

不要使用while (!feof(file)){...},而是使用while(fscanf(file, "%500s", string) == 1){...}

如前所述,使用while(ans[0]=='y')。或者使用

char ans;
scanf(" %c", &ans);//note the blank space before `%c`
while(ans == 'y')

您还忘记了中断 switch 语句。请尝试以下操作:

char c;
char ans;
do {
    printf("What do you want to do?\n");
    printf("1. Write text to file\n");
    printf("2. Read text file\n");
    scanf("%d", &choice);

    switch(choice) {
    case 1:
        printf("Give name to the file (*.txt).\n");
        scanf("%s", nameFile);
        file = fopen(nameFile, "w");
        if(file == NULL) { printf("Could not open the file."); return -1; }
        printf("Input text:\n");

        while((c = getchar()) != '\n' && c != EOF);
        fgets(string, sizeof(string), stdin);
        string[strcspn(string, "\r\n")]=0;

        fprintf(file, "%s", string);
        printf("\n\t\t\t-----------Ended writing.------------\n");
        fclose(file);
        break;
    case 2:
        printf("Give name to the file (*.txt)");
        scanf("%s", nameFile);
        file = fopen(nameFile, "r");
        if(file == NULL) { printf("Could not open the file."); return -1; }
        while(fgets(string, sizeof(string),file))
            printf("%s\n", string);
        fclose(file);
        break;
    }
    printf("Do you want to restart the program? (y/*)");
    scanf(" %c", &ans);
} while(ans == 'y');

另请参阅
Why is “while ( !feof (file) )” always wrong?
How to clear input buffer in C?

【讨论】:

  • 谢谢,它确实有效,但是如果我想将文本写入带有空格的文件,我该怎么办?使用简单的“%s”,或者如您所建议的“%499s”,它确实显示了 然后我可以输入文本,但它在空格后丢失了我的单词。我应该怎么做才能将文本写入带有空格的文件?
  • 在这种情况下,您需要清除缓冲区并使用fgets,请参阅我添加的链接。您还需要fgets 一次读取一行文件。见编辑。
【解决方案2】:

你的时间应该是

 while(ans[0]=='n');

char 数组是一个字符串,您试图将整个字符串与字符 'y' 进行比较。此外,它应该“循环 while ans[0] is equal to 'n'”意味着如果用户指定 n,则继续。

【讨论】:

  • 感谢您解释while循环,它终于奏效了。这是解决了一个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
  • 2016-09-23
  • 2012-08-26
相关资源
最近更新 更多