c - 从C中的同一个txt文件中读取字符串和整数

标签 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;
}

最佳答案

您的问题有两种解决方案。第一种是使用 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() 的返回值以确保读取所有元素。此外,可以通过使用 fscanf(myfile, ...) 来避免使用 fgets()

关于c - 从C中的同一个txt文件中读取字符串和整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49371425/

相关文章:

c++ - 在匿名的情况下使用 libcurl 检索 github 版本

c - 结构体中的嵌套定义

c - SIGSEGV,(貌似)由 printf 引起

c - fork() 之后创建的子进程的父 pid_t

c++ - 体系结构 x86_64 安装库的 undefined symbol

c++ - ARMv5 上的 Valgrind

c - 为什么将函数参数传递给结构初始化会返回垃圾或看似没有执行任何操作?

c - 当我插入较大的数字时程序崩溃

c - 如何正确避免 avformat_new_stream 的 avcodec_alloc_context3 泄漏?

c - 测试本地用户登录数据