从C中的相同txt文件中读取字符串和整数

时间:2018-03-19 20:00:00

标签: c

我对编程很陌生。我用C编写了一个程序,它在txt文件的每一行中读取2个字符串变量和1个整数变量。我已经使用strtokstrdup来分隔每行的第一个和第二个字符串变量,但我不知道如何使用第三个变量执行此操作以使程序将其视为整数...

txt文件就像:

jb12, No1, 13  
jto185, No2, 10  
500grl, No3, 24    
effer, No2, 8  
1801, No1, 6  
120B, No3, 18  
tripl, No4, 2  
etb460, No5, 5  

代码:

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

#define STRING_SIZE 10
#define LINESIZE 128
#define SIZE 8

struct mold_data {

char mold_type[STRING_SIZE];  
char box_type[STRING_SIZE];  
int box_capacity;   
};

struct mold_data array[SIZE];

 int main (){

 int nob;
 float quantity;
 float num_of_boxes;
 char mold_inserted[STRING_SIZE]; 

 FILE *myfile = fopen ("Mold_data_for_all_clients.txt", "r" );
 int i=0;
 int j=0;
 int k=0;
 int l=0;
 char *result[4][3];
 char line[LINESIZE];
 char *value;

 for(i=0; i<=3; i++){
    for(j=0;j<=2;j++){
        result[i][j] = NULL;
    }
}
i=0;

printf("Type mold type");
scanf("%s",mold_inserted);  
printf("Type ordered quantity");  
scanf("%f",&quantity);    

// loop through each entry in "Mold_data_for_all_clients" file //

while(fgets(line, sizeof(line), myfile)){  

    //load mold name
    value = strtok(line, ", ");
    result[i][0] = strdup(value);
    array[i].mold_type==result[i][0];

    //load box type
    value = strtok(NULL, ", ");
    result[i][1] = strdup(value);
    array[i].box_type==result[i][1];


    // load box capacity
    value = strtok(NULL, ", ");
    result[i][2] = strdup(value);
    array[i].box_capacity==result[i][2];


if (strcmp(mold_inserted,result[i][0])==0)

    {
    num_of_boxes=quantity/array[i].box_capacity;
    nob=ceil(num_of_boxes);

    printf("\n %d   " "%s",nob,result[i][1]);  }
    break;

    //go to next line
    i++;
}   


fclose(myfile);
return 0;
}

1 个答案:

答案 0 :(得分:0)

您的问题有两种解决方案。第一种是使用atoi()将字符串转换为整数,如下所示:

array[i].box_capacity = atoi(value);

另一个解决方案是使用sscanf()来解析你的行:

sscanf(line, "%10[^,]s, %10[^,]s, %d", array[i].mold_type, array[i].box_type, &array[i].box_capacity);

此处,%10[^,]s表示除逗号外的任何字符的字符串,最大长度为10个字符。注意:您应该检查sscanf()的返回值,以确保您阅读所有元素。此外,也许可以避免使用fgets()代替fscanf(myfile, ...)

相关问题