简体   繁体   English

读取txt文件中的数字列表并存储到数组C

[英]Read list of numbers in txt file and store to array C

我在阅读数字时遇到问题。运行程序后一切正常,但数组中没有数字。我尝试了不同的方法在文件中写入数字,但没有结果。

FILE *myFile;
myFile = fopen("numbers.txt", "r");
if (myFile==NULL)
{
    printf("Error Reading File\n");
}
else
{
tek=0;
for (i=0;i++)
{
//  tek=fgetc(myFile);
    fscanf(myFile,"%d",&tek);
    if (tek!=EOF)
    {
        redica[i]=tek;
    }
    else
    {
        break;
    }
}
getch();

Consider the following modification to your code: 考虑对您的代码进行以下修改:

#include <stdio.h>

int main(void) {
    int tek;
    int radica[50];

    // open file
    FILE *myFile = fopen("numbers.txt", "r");
    // if opening file fails, print error message and exit 1
    if (myFile == NULL) {
        perror("Error: Failed to open file.");
        return 1;
    }

    // read values from file until EOF is returned by fscanf
    for (int i = 0; i < 50; ++i) {
        // assign the read value to variable (tek), and enter it in array (radica)
        if (fscanf(myFile, "%d", &tek) == 1) {
            radica[i] = tek;
        } else {
            // if EOF is returned by fscanf, or in case of error, break loop
            break; 
        }
    }

    // close file
    fclose(myFile);
    return 0;
}

Any number read by fscanf will be assigned to tek , and entered in the array radica , until fscanf returns EOF , at which point the loop breaks. fscanf读取的任何数字都将分配给tek ,并输入到radica数组中,直到fscanf返回EOF为止,此时循环中断。 As already mentioned, to determine when end of file is reached, it is not the variable tek that is compared to EOF but rather the return of fscanf . 如前所述,要确定何时到达文件末尾,不是将变量tekEOF相比较,而是将fscanf返回。

我遇到了同样的问题,因为“strcmp”只验证了 7 个字符(+1 是字符串“\\0”的结尾),我通过使用“strncmp”解决了这个问题,基本上是相同的功能,但它接受第三个字符参数,要比较的字符数,在我的情况下,我使用strncmp(string1, string2, strlen(string1))或将strlen(string1)更改为要比较的字符数。

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

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