[英]How to convert from char to int in C reading from a file?
我正在嘗試讀取 C 中的文件,其中每行有四個數字,代表兩點的坐標,然后我試圖找到兩點之間的距離。 為此,我正在逐行讀取文件行,並將其作為 char 數組獲取。 以下是我所做的。
我從 read() 調用的 Output function
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 調用的 function。
int read(){
FILE *file;
char buff[255];
file = fopen("point.dat", "r");
while(!feof(file)){
fgets(buff,255,file);
output(buff);
}
return !feof(file);
}
主function
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
如何在 output function 中將 char 轉換為數組? 我也嘗試了 stoi function,但我收到錯誤消息“stoi 不在范圍內”
在您的 output() function 中,buff[i] 只是一個字符,它不是 atoi() 的字符串 (char*)。 您應該使用 strtok() 使用定界符空間將標記轉換為標記,然后將每個標記傳遞給 atoi()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.