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

标签 c atoi

我在文件中有一个标题行,代表我想要读取的矩阵,例如

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

在本例中,我想做的是读取第一行的“4”。但数字可以是任意长度(在某种程度上)。经过一番搜索后,我发现 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);
}

我在编译时遇到的错误是

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’

我不明白 atoi() 是如何工作的或如何解决这个问题,并且文档对我没有帮助,因为我不明白从示例中我发现 atoi() 的输入可能是如何的一个指针,因为它们似乎只是在示例中输入字符。

最佳答案

首先,atoichar * 作为参数。并且您正在提供char

正如您所说,数字的长度可以是可变的。因此,如果您对以下代码部分进行一些更改,效果会更好。

相反

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

更改为

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

关于c - 使用 atoi() 读取一行中的 2 个单独的整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25858419/

相关文章:

C/C++ 校验位

c - 如何在函数签名中使用匿名枚举声明函数?

c++ - 如何修复 "no matching function for call to ' atoi'"错误?

c++ - C++中字符串转int问题

将数字转换为具有多个参数的字符串

c - C 中的数组传递

c - 我应该使用什么循环以及如何使用?

c - C中是否有一个函数可以检查一个字符是字符还是整数等?

c++ - 将字符串转换为 int (C++)

c - C语言中如何将字符串转换为整数?