【问题标题】:Parse string " comes from a file " to integer将字符串“来自文件”解析为整数
【发布时间】:2012-05-16 18:13:43
【问题描述】:

我正在用 C 语言编写一个程序,它从文件中读取一行并在屏幕上显示这一行 我的作业要求文件必须从文件中获取一个数字并对其进行一些操作。

我得到文件内容并将其放入一个数组中:

while ( fgets ( line, sizeof line, file ) != NULL ) 
    {        
        strcpy(arra[i], line);
        printf("array ----> %d \n", arra[i]);
        i++;        
    }

如何将此内容解析为 int ?

【问题讨论】:

  • 特别是对于家庭作业,可能是scanf。对于严肃的使用,您经常希望使用fgets 后跟sscanf 之类的东西。

标签: c string parsing int


【解决方案1】:

如果linechar*,您可以使用atoi 将其转换为整数。

printf("array ----> %d \n", atoi(line));

【讨论】:

    【解决方案2】:

    你可以使用 atoi()

    int x = atoi("string");
    

    来自您的代码示例

    while ( fgets ( line, sizeof line, file ) != NULL ) 
    {        
        strcpy(arra[i], line);
        printf("array ----> %d \n", atoi(arra[i]));
        i++;        
    }
    

    【讨论】:

    • 您需要为变量命名。
    • 我们同时点击了提交按钮。我们现在是提交好友!
    • @Luchian:我们有提交好友徽章吗?
    • int i = atoi("1234") 将给 i 的值 1234
    • 我认为不是,将 int 转换为 int,或者从文件中读取 int 而不是字符串
    【解决方案3】:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAX_DATA_SIZE 10
    
    int main(){
        FILE *file;
        char line[128];
        int array[MAX_DATA_SIZE];
        int i,count,sum;
    
        file = fopen("data.txt","r");
    /* data.txt:
    100
    201
    5
    -6
    0
    */
        for(i=0; NULL!=fgets(line, sizeof(line), file); ++i){
            if(i == MAX_DATA_SIZE){
                fprintf(stderr,"exceeded the size of the array.\n");
                exit(EXIT_FAILURE);
            }
            array[i]=atoi(line);
        }
        fclose(file);
        /*some operations */
        count = i;
        sum = 0;
        for(i=0;i<count;++i)
            sum += array[i];
        printf("%d\n",sum);
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 2018-01-27
      相关资源
      最近更新 更多