简体   繁体   中英

How to convert from char to int in C reading from a file?

I am trying to read a file in C which has four numbers per line which represents coordinates of two points and then I am trying to find the distance between the two points. For this, I am reading the file lines one by one and I am getting it as a char array. Below is what I have done.

Output function which I am calling from read()

void output(char *buff){
    int co1,co2,co3,co4;
    co1 = atoi(buff[0]);
    co2 = atoi(buff[2]);
    co3 = atoi(buff[4]);
    co4 = atoi(buff[6]);
    printf("(%d,%d) lies on the %s,(%d,%d) lies on the %s, distance is %f.\n",co1,co2,quadrant(co1,co2),co3,co4,quadrant(co3,co4),distance(co1,co2,co3,co4));

}

Read function which I am calling from main.

int read(){
    FILE *file;
    char buff[255];
    file = fopen("point.dat", "r");
    while(!feof(file)){
        fgets(buff,255,file);
        output(buff);
    }
    return !feof(file);
}

Main function

int main()
{
    read();
    return 0;

}

But while doing so, I am getting below error.

[Error] invalid conversion from 'char' to 'const char*' [-fpermissive]

The data of point.dat is

0 0 3 4
-1 -4 5 6
-1 3 -1 -2
4 -5 -5 -6
3 5 -6 5
0 5 5 5 
-5 0 0 -5

How can I convert char to array in output function? I tried stoi function too, but I got error that "stoi is not in scope"

In your output() function, buff[i] is only one char which is not a string (char*) for atoi(). You should use strtok() to buff into tokens using the delimiter space and then pass each token to atoi().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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