如何将字符串存储到txt文件

How to store string to txt file

void inserting()
{
    char file_name[50]; 
    char sentence[1000];
    FILE *fptr;
    printf("File name (With extn):");
    scanf("%s", file_name);
    fptr = fopen(file_name, "a");
    if (fptr == NULL)
    {
        printf("Error!");
        exit(1);
    }
    printf("Enter a sentence:\n");
    scanf("%s", sentence);

    fgets(sentence,sizeof(sentence),stdin);    
    fprintf(fptr, "%s", sentence);
    fclose(fptr);
}

我想将内容从字符串存储到文件...但它显示除第一个单词以外的所有内容...

INPUT : Hello this is C program //which I have entered
OUTPUT: this is C program //this is what stored in file  

如果您想保留您的代码,请进行调整

void inserting(){
        char file_name[50]; 
        char sentence[1000];
        FILE *fptr;
        printf("File name (With extn):");
        scanf("%s", file_name);
        fptr = fopen(file_name, "a");
        if (fptr == NULL)
        {
            printf("Error!");
            exit(1);
        }
        printf("Enter a sentence:\n");
        scanf("%s", sentence);
        fprintf(fptr,"%s",sentence); //<-- HERE
        fgets(sentence,sizeof(sentence),stdin);    
        fprintf(fptr, "%s", sentence);
        fclose(fptr);
    }

或者您可以使用 getline 之类的东西来变得更干净。

#include<stdio.h>

void inserting()
{
    char file_name[50]="C:\Users\Dev Parzival\Desktop\foo.txt";
    char sentence[1000];
    FILE *fptr;
    //printf("File name (With extn):");
    //scanf("%s", file_name);
    fptr = fopen(file_name, "w");
    if (fptr == NULL)
    {
        printf("Error!");
        exit(1);
    }
    printf("Enter a sentence:\n");
    scanf("%[^\n]", sentence);
    printf(sentence);

    //fgets(sentence,sizeof(sentence),stdin);
    fprintf(fptr, "%s", sentence);
    fclose(fptr);
}

int main(){
    inserting();
}

扫描不会读取空格 %s 你必须包含空格我也认为这就是为什么使用 %[^\n] 格式说明符。