简体   繁体   English

使用atoi()读取2个单独的整数值的行

[英]Read a line for 2 separate integer values using atoi()

I have a header line in a file that represents a matrix I want to read, eg 我在文件中有一个标题行,代表我想读取的矩阵,例如

R4 C4
1 0 0 0
0 1 0 0 
0 0 1 0
0 0 0 1

What I want to do is read the first line for the '4's in this case. 在这种情况下,我想读的是第一行的“ 4”。 But the numbers could be of arbitrary length (to some extent). 但是数字可以是任意长度的(在某种程度上)。 After some searching I found that atoi() could do the trick (maybe): 经过一番搜索,我发现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);
}

The error I get at compiling is 我在编译时遇到的错误是

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’

I don't understand how atoi() works or how to fix this, and the documentation doesn't help me because I don't understand from the examples that I have found how the input to atoi() could possibly be a pointer since they seem to just input characters in the examples. 我不了解atoi()的工作方式或解决方法,并且该文档也无济于事,因为我从示例中不了解我发现atoi()的输入可能是一个指针,因为他们似乎只是在示例中输入字符。

First, atoi takes char * as argument. 首先, atoichar *作为参数。 And you are providing char . 并且您正在提供char

As you said that numbers can be of variable length. 如您所说,数字可以是可变长度的。 So it will be better if you make some change in the below part of your code. 因此,如果您在代码的以下部分进行一些更改,将会更好。

Instead 代替

if(c == 'R'){
    c = fgetc(pFile);
    rows = atoi(c);
    }
    if(c == 'C'){
    c = fgetc(pFile);
    columns = atoi(c);
    break;
    }

change it to 更改为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM