C:使用 do while 循环写入/读取文件

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

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

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

有人可以解释一下我做错了什么以及如何解决这个问题吗?我将不胜感激。

这是我的代码:

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

最佳答案

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?

关于C:使用 do while 循环写入/读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47519580/

相关文章:

c - 作业,链表冒泡排序

R包lda中折叠的吉布斯采样

angular - 根据 Angular 值的变化禁用/启用按钮

c - 如何在 C 中按值对数组中的每个元素进行 "delete"

java - 尝试获取代码来检查是否有偶数括号

c - 在 C 中计算大小写字母的问题

c - 通过函数初始化C结构

android - 更改 EditText 错误信息的背景

javascript - 如何在 createElement 输入上设置与先前输入相同的字体大小? [Javascript]

在 Notepad++ 中编译和运行C代码