Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用atoi()读取两个独立整数值的行_C_Atoi - Fatal编程技术网

C 使用atoi()读取两个独立整数值的行

C 使用atoi()读取两个独立整数值的行,c,atoi,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 linc

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

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的输入可能是指针,因为它们似乎只是示例中的输入字符。

首先,atoi将char*作为参数。你提供的是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之后的数字,否则您的文件格式不正确。正如我正确理解的那样,fscanf将进行扫描,直到它到达数字和C之间的空格?例如:R4 C4Yes,它将连续数字作为一个整数读取,直到出现空白。