将字符串(char)转换为数组(int)

时间:2012-06-24 16:10:28

标签: c string

我有一个包含一些int变量的file.txt。我需要将第三个数字转换为int array,这样我就可以按照我想要的方式操作数据:

EX: file.txt
============

111111 1001 20120131 30
122222 2002 20110230 25
133333 3003 20100325 12
144444 1001 20110526 18
155555 1001 20100524 25
166666 2002 20120312 30
177777 2003 20120428 28
188888 3003 20111214 15
199999 3002 20101113 27
199999 1001 20101202 29
133333 1001 20120715 25
155555 1001 20100204 24
177777 3003 20110102 30    

我需要逐行读取文件,并选择了fscanf函数:

FILE *fp;

int n1, n2, n4;
char n3[9];
int array[9]

[...]

while (fscanf (fp, "%d %d %s %d", &n1, &n2, n3, &n4);

现在我有了我的字符串,如何将其转换为int数组? 我尝试过:

for (i = 0; i < strlen(n3); i++)
    array[i] = atoi(strlen[i])

但它出错了......我怎么解决这个问题?

它回到我身边:

warning: passing argument 1 of ‘atoi’ makes pointer from integer without a cast [enabled by default]
/usr/include/stdlib.h:148:12: note: expected ‘const char *’ but argument is of type ‘char’

4 个答案:

答案 0 :(得分:2)

您需要以下内容:

int array[HUGE];

for (int i = 0; i < HUGE && fscanf(fp, "%d %d %s %d", &n1, &n2, n3, &n4) == 4; ++i)
{
    array[i] = atoi(n3);
}

基本问题是,如果您不知道文件有多少行,那么您不知道创建收件人数组有多大。更安全的解决方案是使用包含mallocrealloc的动态数组。

在这方面,将字符串读入char[9]是非常非常危险:如果文件包含错误的数据,则程序会死亡,或者更糟。使用fgets首先将文件逐行读入字符串会更安全,然后分别对每行进行标记和解析,例如,使用strtoul

答案 1 :(得分:1)

至少在我理解你的问题时,你只关心第三栏中的数字。假设是这样,我想我会做更多这样的事情:

for (i=0; i<elements(array); i++)
    if (0 == fscanf(infile, "%*d %*d %d %*d", array+i))
        break;

答案 2 :(得分:1)

如果您真的只想将第三个元素作为整数,那么为什么不在调用fscanf时以整数形式读取它?即,我认为以下内容将大致按照您的要求进行:

#define MAX_VALUES 9

FILE *fp;

int n1, n2, n3, n4;
int array[MAX_VALUES]
int num_values;

while (fscanf (fp, "%d %d %d %d", &n1, &n2, &n3, &n4) && (num_values<MAX_VALUES))
    array[num_values++] = n3;

答案 3 :(得分:0)

如果你想要每行8个单位的数组,那么你可以这样做:

for ( i = 0; i < 8; i++ ) {
    array[i] = n3[i] - '0';
}

然而,正如其他人所说,依赖文件的格式为n3 []和array []的长度并不是一个好主意,即使我用8替换strlen()时也是如此。

我可能strtok()每行使用空格作为分隔符,然后对数据进行一些验证以确保它符合您的想法。

P.S。第三列看起来像一个日期,你确定要一个int数组吗?

相关问题