我对编程还很陌生。我用 C 编写了一个程序,它在 txt 文件的每一行中读取 2 个字符串变量和 1 个整数变量。我已经使用 strtok
和 strdup
来分隔每行的第一个和第二个字符串变量,但我不知道如何使用第三个变量来做到这一点,以便使程序将其视为整数...
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/