Search code examples
catoi

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, e.g.

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. But the numbers could be of arbitrary length (to some extent). After some searching I found that atoi() could do the trick (maybe):

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.


Solution

  • First, atoi takes char * as argument. And you are providing 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;
        }