c - 在 C 中将字符作为整数添加到数组中

标签 c file-io type-conversion atoi

我正在尝试将整数添加到 C 中的数组中。但是我正在从文件中读取字符,因此我必须首先将它们转换为整数。 由于某种原因,我的程序在停止工作之前甚至无法启动。我认为这是一个转换问题,但我是 C 新手。

新的编辑代码:

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

int main (void)
{
    FILE* fp;
    const char filename[] = "test.txt";
    char ch;
    int num[1000];
    int j = 0;
    char temp;

    fp = fopen(filename, "r");
    if( fp == NULL )
    {
        printf( "Cannot open file: %s\n", filename);
        exit(8);
    }

    while(!feof(fp))
    {
        temp = fgetc(fp);
        num[j] = temp - '0';
        j++;
    }
    printf("First in the array is: %d,  last is; %d", num[0], num[999]);


    fclose(fp);

    return EXIT_SUCCESS;
}

测试.txt

731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511
125406987471585238630507156932909632952274430435576689664895044524452316173185640309871112172238311362229893423380308135336276614282806444486645238749
303589072962904915604407723907138105158593079608667017242712188399879790879227492190169972088809377665727333001053367881220235421809751254540594752243
525849077116705560136048395864467063244157221553975369781797784617406495514929086256932197846862248283972241375657056057490261407972968652414535100474
821663704844031998900088952434506585412275886668811642717147992444292823086346567481391912316282458617866458359124566529476545682848912883142607690042
242190226710556263211111093705442175069416589604080719840385096245544436298123098787992724428490918884580156166097919133875499200524063689912560717606
0588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450

有人为我指明正确的方向就太好了。

最佳答案

在您添加 test.txt 的内容后,我将重新表述我的整个答案。

而不是

while(!feof(fp))
{
    temp = fgetc(fp);
    num[j] = temp - '0';
    j++;
}

更改为

while(!feof(fp)&& (j<1000))
{
    temp = fgetc(fp);
    if ( temp != EOF && ( temp>='0' && temp<='9') ) // To filter out non-numbers and also the last EOF
       num[j++] = temp - '0';

}

而不是

printf("First in the array is: %d,  last is; %d", num[0], num[999]);

更改为

printf("First in the array is: %d,  last is; %d", num[0], num[j-1]); // j-1 so that it works even when there are less than 1000 numbers and to keep it generic

你完成了!

关于c - 在 C 中将字符作为整数添加到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9583415/

相关文章:

c - 在 WinAPI 中重置信号量计数器

wpf - 无法删除其他进程使用的文件

java - 使用NIO解码器会导致读取整个文件吗?

java - 在 Java 整数上,Character.IsDigit 返回 false 而不是 true

c++ - 是否存在从 std::shared_ptr<T> 到 std::shared_ptr<const T> 的隐式转换?

c - cp 中的二维数组

c - C 是否总是评估所有与 && 或 || 相关的语句?

c - 重复完全相同的代码段 1000 次而不循环

java - 从 json 文件中读取多个元素

java泛型方法调用转换错误