C语言 - 打印一些句子到文件

时间:2017-01-13 18:53:35

标签: c

我想读取字符串并将它们作为实线写入文件,但我不能将更多单词作为完整的字符串读入缓冲区。

当前有问题的代码:

printf("\nEnter how many sentences do you want to read: ");
    scanf("%d", &n);
    tab = (char**)malloc(n * sizeof(char*));
        for (int i = 0; i < n; i++) {
            printf("\nEnter sentence: ");
            scanf("%s", val);
            tab[i] = _strdup(val);
        }
        for (i = 0; i < n; i++)
            fprintf(f, "%s ", tab[i]);
        free(tab);

以前我试过这个: (问题是这只会分配一个字符串)

printf("\nEnter how many sentences do you want to read: ");
    scanf("%d", &n);
    for (i = 0; i < n; i++) {
        printf("\nEnter sentence: ");
        scanf("%s", val);
        fprintf(f, "\%s ", val);
    }

几乎在那里,现在我有句子,但我有一行空行作为第一行文件。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string>
#define SIZE 30

void creare(char t[30]);

void main(void)
{
    FILE* f2;
    char name[30];
    printf("\nEnter name of file to work with: ");
    scanf("%s", name);
    creare(name);
    f2 = fopen(name, "r");
    if (f2 == NULL)
    {
        printf("\nOpen error!!");
        exit(0);
    }
    fclose(f2);
    printf("\n");
    _getch();
}


void creare(char t[30])
{
    FILE* f;
    int n,i;
    char val[30];
    f = fopen(t, "w");
    if (f == NULL)
    {
        printf("\nOpen error!!");
        exit(0);
    }
    printf("\nEnter how many sentences do you want to read: ");
    scanf("%d", &n);
    for (i = 0; i <= n; i++)
    {
        fgets(val, sizeof(val), stdin);
        fprintf(f, "% s", val);
    }
    fclose(f);
}

1 个答案:

答案 0 :(得分:2)

我使用fgets(val,sizeof val,stdin)来读取字符串,因为要读取带空格的字符串。 该空白行存档的原因是由于您正在阅读&#34; \ n&#34;在scanf之后输入(&#34;%d&#34;,&amp; n);击键&#34; \ n&#34;将首次读入val,因此它只是打印出&#34; \ n&#34;到文件。

为了阅读&#34; \ n&#34;用一个字符来读取&#34; \ n&#34;。以下是完整的计划。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#define SIZE 30

void creare(char t[30]);

int main(void)
{
    FILE* f2;
    char name[30];
    printf("\nEnter name of file to work with: ");
    scanf("%s", name);
    creare(name);
    f2 = fopen(name, "r");
    if (f2 == NULL)
    {
        printf("\nOpen error!!");
        exit(0);
    }
    fclose(f2);
    printf("\n");
}


void creare(char t[30])
{
    FILE* f;
    int n,i;
    char val[30],g;
    f = fopen(t, "w");
    if (f == NULL)
    {
        printf("\nOpen error!!");
        exit(0);
    }
    printf("\nEnter how many sentences do you want to read: ");
    scanf("%d", &n);
    scanf("%c",&g);
    for (i = 0; i <n; i++)
    {
        fgets(val, sizeof(val), stdin);
        fprintf(f, "%s", val);
    }
    fclose(f);
}