【问题标题】:How to convert from char to int in C reading from a file?如何在从文件中读取的 C 中从 char 转换为 int?
【发布时间】:2020-07-17 04:15:55
【问题描述】:

我正在尝试读取 C 中的文件,该文件每行有四个数字,代表两点的坐标,然后我试图找到两点之间的距离。为此,我正在逐行读取文件行,并将其作为 char 数组获取。以下是我所做的。

我从 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));

}

读取我从 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);
}

主要功能

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

}

但是这样做时,我遇到了错误。

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

point.dat的数据是

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

如何在输出函数中将 char 转换为数组?我也尝试了 stoi 函数,但出现“stoi 不在范围内”的错误

【问题讨论】:

  • atoi() 参数的类型应该是 const char * 并且您传递给它的是 char 类型。
  • 如何将其更改为 const char*?
  • 你会想看看Why is while ( !feof (file) ) always wrong? 另外,不要在函数中硬编码文件名。要么将其作为输入读取,要么将其作为参数传递给int main (int argc, char **argv),然后打开并验证文件是否在调用者中打开(此处为main())并将打开的FILE* 作为参数传递给read() 函数。
  • 对不起,我无法从stackoverflow.com/questions/4600797/…得到它
  • 我也用过,但还是出错了。 @H.S.

标签: c char int


【解决方案1】:

在你的 output() 函数中,buff[i] 只是一个字符,它不是 atoi() 的字符串 (char*)。您应该使用 strtok() 将使用分隔符空间的标记转换为标记,然后将每个标记传递给 atoi()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 2011-01-05
    • 1970-01-01
    • 2012-06-06
    • 2019-10-16
    • 2017-04-17
    • 1970-01-01
    相关资源
    最近更新 更多