如何在C编程中从文件中一起读取和打印所有不同的数据类型

问题描述 投票:1回答:1

我的代码如下。如果运行此代码,则即使正确创建了文本文件,由于某种原因,垃圾值也会在控制台中打印出来。当我包含字符串时,只有字符串会在控制台窗口中正确读取和打印,并且我得到其余变量的垃圾值,但是当我完全扣除字符串时,我会得到其余变量的正确值。为什么会出现此问题以及如何解决?这是代码:

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
    char str[]= "a string";
    char str2[50];
    char ch ='a';
    char ch1;
    int num = 12;
    int num1;
    float deci = 51.15;
    float deci1;

    FILE *new;

    new = fopen("a.txt","w");


    if(new == NULL)
    {
        printf("Error! file not found! \n");
    }
    fprintf(new, "%s\n", str);
    fprintf(new, "%c\n", ch);
    fprintf(new, "%d\n", num);
    fprintf(new, "%.2f\n", deci);

    fclose(new);

    new = fopen("a.txt","r");


    if(new == NULL)
    {
        printf("Error! file not found!  \n");
    }

    fscanf(new, "%[^\n]s", str2);
   //str2[7]='\0';

    fflush(stdin);
    fscanf(new, "%c", &ch1);
    fscanf(new, "%d", &num1);
    fscanf(new, "%f", &deci1);

    //fclose(new);

    printf("string: %s character: %c integer: %d float: %f",str2,ch1,num1,deci1);
    enter code here
    fclose(new);

}
c string file char int
1个回答
0
投票

如果我没记错的话,错误就在这里:

fscanf(new, "%[^\n]s", str2); 

尝试使用以下方法进行更改:

fscanf(new, "%[^\n]\n", str2);

这确实对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.