简体   繁体   English

从txt文件读取并输入到C中的数组

[英]Read from txt file and input to an array in C

I have my txt file 我有我的txt文件

4  
110  
220  
112  
335 

4 is the number of lines and 4*3 the number of int. 4是行数和4 * 3的int数。 I have to read "4" then read the remaining and input them into an array 我必须读“4”然后读取剩余的并将它们输入到数组中

This is what I have 这就是我所拥有的

void main(){ 
    int a,n;    
    int i=0,j=0,k[30]; //
    int *N;

    FILE *fp = fopen("test.txt", "r");  
    if(fscanf(fp, "%d", &a) != 1) { //
       // something's wrong 
    }

    n=3*a; //3*a numbers in the file
    N = malloc(3 * a * sizeof(int)); 
    for(i = 0; i <n;++i) {
       int result=fscanf(fp, "%d", &N[i] );  
    }   
    fclose(fp);  
    for(j=0;j<3*a;j++){  
       k[j]=N[j]; 
    }

    printf("%d",k[0]);
 }

When I print k[0] it was supposed to print "1" but instead the whole line "110" is printed 当我打印k[0]它应该打印“1”,而是打印整行“110”

Is there any other way to do this??? 还有其他办法吗?

The format specifier %d does not specify a length, so fscanf will read as many digits as it can; 格式说明符%d没有指定长度,因此fscanf将读取尽可能多的数字; this is why you get 110 instead of just 1. 这就是为什么你得到110而不是1。

If you specify a length, like %1d , it will only read as many digits as you tell it to: 如果您指定一个长度,例如%1d ,它将只读取您告诉它的数字:

for(i = 0; i <n;++i) {
   int result=fscanf(fp, "%1d", &N[i] );  
}   

When you use fscanf with %d format parameter, it retrieves an integer type from the file. 当您使用带有%d格式参数的fscanf时,它会从文件中检索整数类型。 Since 110 and the others are all integers, it will directly fetch 110 from file. 由于110和其他都是整数,它将直接从文件中获取110。

So you can either use fscanf with %d parameters in a loop which iterates for a times, or if you want to get it character by character, you can use fscanf with %c parameter but it needs much more effort. 所以你可以在一个循环中使用带有%d参数的fscanf进行迭代一次,或者如果你想逐个字符地获取它,你可以使用带有%c参数的fscanf,但它需要更多的努力。 So, you should use fscanf with %d parameter and fetch all digits from it by a loop for every number. 因此,您应该将fscanf与%d参数一起使用,并为每个数字循环获取所有数字。

The fscanf(fp, "%d", &N[i] ) will catch a number and not a digit. fscanf(fp, "%d", &N[i] )将捕获一个数字而不是一个数字。 So 所以

fscanf(fp, "%d", &N[0] )  //will catch 110
fscanf(fp, "%d", &N[1] )  //will catch 220
...

If you want to catch digits in your array you have to use the following code: 如果要捕获数组中的数字,则必须使用以下代码:

for(i = 0; i <n;++i) {
    int result=fscanf(fp, "%c", &N[i] );
    if (isdigit (N[i])) N[i]-='0';
    else i--;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM