我在文件中有一个标题行,代表我想要读取的矩阵,例如
R4 C4
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
在本例中,我想做的是读取第一行的“4”。但数字可以是任意长度(在某种程度上)。经过一番搜索后,我发现 atoi() 可以解决这个问题(也许):
int main ()
{
FILE * pFile;
FILE * pFile2;
pFile = fopen ("A.txt","r");
pFile2 = fopen ("B.txt","r");
char c;
int lincount = 0;
int rows;
int columns;
if (pFile == NULL) perror ("Error opening file");
else{
while ((c = fgetc(pFile)) != '\n')
{
if(c == 'R'){
c = fgetc(pFile);
rows = atoi(c);
}
if(c == 'C'){
c = fgetc(pFile);
columns = atoi(c);
break;
}
}
lincount++;
printf("Rows is %d and Columns is %d\n", rows, columns);
}
我在编译时遇到的错误是
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’
我不明白 atoi() 是如何工作的或如何解决这个问题,并且文档对我没有帮助,因为我不明白从示例中我发现 atoi() 的输入可能是如何的一个指针,因为它们似乎只是在示例中输入字符。
最佳答案
首先,atoi
将 char *
作为参数。并且您正在提供char
。
正如您所说,数字的长度可以是可变的。因此,如果您对以下代码部分进行一些更改,效果会更好。
相反
if(c == 'R'){
c = fgetc(pFile);
rows = atoi(c);
}
if(c == 'C'){
c = fgetc(pFile);
columns = atoi(c);
break;
}
更改为
int row;
int column;
if(c == 'R'){
fscanf(pFile, "%d", &row);
//rows = atoi(c); <----No need of atoi
}
if(c == 'C'){
fscanf(pFile, "%d", &column);
//columns = atoi(c); <----No need of atoi
break;
}
关于c - 使用 atoi() 读取一行中的 2 个单独的整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25858419/