读取C编程的文本文件,并存储在阵列 [英] read text file and store in array in c programming

查看:99
本文介绍了读取C编程的文本文件,并存储在阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要读阵列文本文件并存储然后显示出来。

I want read text file and store in array then show.

这是我的code:

  int i = 0, line = 5;
  char ch[100];

  FILE *myfile;
    myfile = fopen("test.txt","r");
    if (myfile== NULL)
    {
    printf("can not open file \n");
    return 1;
    }

    while(line--){
    fscanf(myfile,"%s",&ch[i]);
    i++;
    printf("\n%s", &ch[i]);
    }

    fclose(myfile);

    return 0;
}

这是我的文字:

测试123562

856

59986

但结果是:

EST

2356

56

9986

什么是错的? (

推荐答案

<击> CH [I] 持有单个字符。声明的fscanf(MYFILE,%S,&安培; CH [i]); 将扫描字符串 CH [I] 可容纳只有一个字符。没有为无处'\\ 0'这会导致你的程序的未定义行为即可。
更改

ch[i] is holding a single character. Statement fscanf(myfile,"%s",&ch[i]); will scan string to ch[i] which can hold only one character. There is no place for '\0' which leads your program to undefined behavior. Change

fscanf(myfile,"%s",&ch[i]);  

fscanf(myfile,"%s",ch);

previous答案是错的。节目的行为是明确的,但你是在一个错误的方式扫描文件。你的程序将如预期,如果你把我++; 的printf 语句。

Previous answer was wrong. Behavior of program is well defined but you are scanning the file in a wrong manner. Your program will work as expected if you place i++; after printf statement.

while(line--){
    fscanf(myfile,"%s",&ch[i]);
    printf("\n%s", &ch[i]);
    i++;
}   

原因是,&放大器; -CH [I] 是一个指向I 数组和字符串的元素将被存储在数组以位置 I 。对于给定的输入,这会起作用,因为给定的数组大到足以容纳字符串。

The reason is that &ch[i] is a pointer to the ith element of the array and string will be stored in array starting at position i. For the input given, this will work because the given array is large enough to hold the string.

您可以这样做的:

while(line--){
    fscanf(myfile,"%s",ch);
    printf("\n%s", ch);
    i++;
}   

但它会覆盖阵列 CH 每个字符串进行扫描,以它的时间。最好使用一个二维数组来存储字符串和读取文件与fgets

but it will overwrite the array ch each time a string is scanned to it. Better to use a two dimensional array to store strings and read file with fgets.

这篇关于读取C编程的文本文件,并存储在阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆