在C语言中将字符作为整数添加到数组中
我试图在C中向数组中添加整数。但是我从文件中读取字符,所以我必须首先将它们转换为整数。 由于某些原因,我的程序在停止工作之前甚至不会启动。我认为这是一个转换的问题,但我是新的C 新编辑代码:在C语言中将字符作为整数添加到数组中,c,file-io,type-conversion,atoi,C,File Io,Type Conversion,Atoi,我试图在C中向数组中添加整数。但是我从文件中读取字符,所以我必须首先将它们转换为整数。 由于某些原因,我的程序在停止工作之前甚至不会启动。我认为这是一个转换的问题,但我是新的C 新编辑代码: #include <stdio.h> #include <stdlib.h> int main (void) { FILE* fp; const char filename[] = "test.txt"; char ch; int num[1000]
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
FILE* fp;
const char filename[] = "test.txt";
char ch;
int num[1000];
int j = 0;
char temp;
fp = fopen(filename, "r");
if( fp == NULL )
{
printf( "Cannot open file: %s\n", filename);
exit(8);
}
while(!feof(fp))
{
temp = fgetc(fp);
num[j] = temp - '0';
j++;
}
printf("First in the array is: %d, last is; %d", num[0], num[999]);
fclose(fp);
return EXIT_SUCCESS;
}
有人给我指出正确的方向会很好。你不能像这样在C中动态分配一个int数组,所以
int num[count]
这是行不通的。使用最大值或使用malloc的动态分配
此外,您不能将单个字符传递给atoi,您必须传递第二个元素为0的2元素字符数组,或者您可以使用
num[j] = temp - '0';
在第二个while循环中检查fp是否存在EOF错误时,请使用feof(fp)
或temp!=EOF
希望这对您的工作有所帮助。以下应用程序工作并提供以下输出(在包含1 3 5 5565的文本文件中) 如果希望数组具有动态大小,则需要在添加元素之前循环遍历元素并对其进行计数,就像在主代码的示例中所做的那样。而不是
while(fscanf(fp,“%d”,&num[count])!=EOF){
使用临时计数器对元素进行索引
希望这有帮助在您添加了
test.txt
的内容后,我正在重新表述我的整个答案
而不是
while(!feof(fp))
{
temp = fgetc(fp);
num[j] = temp - '0';
j++;
}
printf("First in the array is: %d, last is; %d", num[0], num[999]);
改为
while(!feof(fp)&& (j<1000))
{
temp = fgetc(fp);
if ( temp != EOF && ( temp>='0' && temp<='9') ) // To filter out non-numbers and also the last EOF
num[j++] = temp - '0';
}
改为
printf("First in the array is: %d, last is; %d", num[0], num[j-1]); // j-1 so that it works even when there are less than 1000 numbers and to keep it generic
您的操作完成了!我在新的编辑中加入了您的更改,但程序仍然无法运行。实际上,可以像以前一样使用变量启动数组:array[arraySize]。尽管不允许“调整大小”例如,在循环中,如果它超出边界,它将被忽略。然后你需要创建一个新的更大的数组并将值复制到该数组中。假设这取决于你的文本文件的外观。EOF表示行尾、ei enter或空格,因此每个元素都需要使用该POST来分隔,你的文本文件包含什么,我可以查看一下。上面的代码很有效我的comp很好,你的也可以:)你所有的数字都是一位数吗?因为在循环中你只把一个字符转换成一个整数!在你添加了
test.txt
的内容后,我发布了一个新的答案。看看它是否有效!
printf("First in the array is: %d, last is; %d", num[0], num[999]);
printf("First in the array is: %d, last is; %d", num[0], num[j-1]); // j-1 so that it works even when there are less than 1000 numbers and to keep it generic