Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.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
如何将文件中的字符转换为ascii整数并转换为数组?_C_Arrays_Io - Fatal编程技术网

如何将文件中的字符转换为ascii整数并转换为数组?

如何将文件中的字符转换为ascii整数并转换为数组?,c,arrays,io,C,Arrays,Io,我试图将字符和整数的列表放入一个仅包含整数的数组中。file.txt看起来像: a 5 4 10 4 10 a 4 在数组中,我希望值显示为{97,5,4,10,4,10,97,4} 这是我代码的一部分: int * array = malloc(100 * sizeof(int)); FILE* file; int i=0; int integer = 1; file=fopen(filename,"r"); while (fscanf(file,"%d",&integer)

我试图将字符和整数的列表放入一个仅包含整数的数组中。file.txt看起来像:

 a 5 4 10 
 4 10 a 4
在数组中,我希望值显示为{97,5,4,10,4,10,97,4} 这是我代码的一部分:

int * array = malloc(100 * sizeof(int));
FILE* file;
int i=0;
int integer = 1;
file=fopen(filename,"r");
while (fscanf(file,"%d",&integer) > 0)
{
    array[i] = integer;
    i++;

}    

在我看来,您要做的是使用
fscanf(“%s”,一些字符串)
,因为数字可以作为字符串接收,但字符串不能作为数字接收。然后,对于每个输入,您需要确定字符串是否实际为数字,然后相应地导出要放入数组中的值。

您的问题是,在第一次读取时,while条件将退出,因为文件中的第一个元素是字符,不会将其解释为整数,返回0。我建议,如果您确定分隔符是一个空格,则读取一个字符串(它将自动在空格处停止),并使用将读取的值转换为int

比如:

int * array = malloc(100 * sizeof(int));
FILE* file;
int i=0;
char tmp[2], *pEnd;
file=fopen("./test.txt","r");
while (fscanf(file,"%s",tmp) > 0)
{
    if( !(array[i] = strtol(tmp, &pEnd,10)))
         array[i] = tmp[0];
    i++;
}
注意,我假设没有大于一位的整数(
tmp
array size),我检查
strtol
响应以检测非整数字符