使用fscanf计算文本文件中的整数数
例如,我有一个包含所有整数的txt文件。我想计算有多少个整数来分配一个数组使用fscanf计算文本文件中的整数数,c,file,scanf,C,File,Scanf,例如,我有一个包含所有整数的txt文件。我想计算有多少个整数来分配一个数组 int array[0]; int count = 0; FILE *file = fopen("file1.txt","r"); while(fscanf(file,"%d",&array[count])==1){ count++; } printf("%d",count); 目前有错误消息,无法通过。这就是fscanf的工作方式吗 无法创建大小为0的数组。如果只想计算整数的数量,请不要使用数组,而只使用
int array[0];
int count = 0;
FILE *file = fopen("file1.txt","r");
while(fscanf(file,"%d",&array[count])==1){
count++;
}
printf("%d",count);
目前有错误消息,无法通过。这就是fscanf的工作方式吗 无法创建大小为0的数组。如果只想计算整数的数量,请不要使用数组,而只使用临时变量。 检查是否正确打开了文件并关闭文件是一个好主意
#包括
int main(){
内部温度;
整数计数=0;
FILE*FILE=fopen(“file1.txt”、“r”);
if(file==NULL){
printf(“无法打开指定的文件”);
返回-1;
}
而(fscanf(文件“%d”,&temp)==1){
计数++;
}
fclose(文件);
printf(“%d”,计数);
}
返回0;
}
如果您还希望存储值以供以后使用,例如,您可以将该文件读取两次,第一次计算整数的数量,然后使用该数量声明所需的数组。在第二次运行之前,一件重要的事情是倒带文件指针,从一开始就读取文件
#include <stdio.h>
int main(){
int temp;
int count = 0;
FILE *file = fopen("file1.txt","r");
if(file == NULL){
printf("Could not open specified file");
return -1;
}
while(fscanf(file,"%d",&temp)==1){
count++;
}
printf("%d",count);
if(count == 0){ //do not create array of size 0
fclose(file);
}
else{
//second run
int array[count];
rewind(file);
for(int i=0; i<count; i++){
fscanf(file,"%d",&array[count]);
}
fclose(file);
//continue using array...
}
return 0;
}
#包括
int main(){
内部温度;
整数计数=0;
FILE*FILE=fopen(“file1.txt”、“r”);
if(file==NULL){
printf(“无法打开指定的文件”);
返回-1;
}
而(fscanf(文件“%d”,&temp)==1){
计数++;
}
printf(“%d”,计数);
如果(count==0){//不要创建大小为0的数组
fclose(文件);
}
否则{
//第二轮
整数数组[计数];
倒带(文件);
对于(int i=0;i
及
将导致分段错误,因为您访问数组超出范围
如果您需要灵活的阵列,您需要
int*数组
- 用于存储
fscanf
realloc
array每次您找到一个新号码并将该号码添加到数组中时
#包括
#定义isDigit(c)('0'“有错误消息”?哪些错误消息?编译时间还是运行时间?检查fopen
是否有效。为什么要使用array
。其中的段错误请检查file
是否为NULL
@EdHealint-array[0];
whaaat?“我想计算有多少个整数”-->文件中是否有除整数以外的任何内容,如“123 x 456”
?请添加可以打开file@EdHeal感谢您的提及,我更新了answerMinor:缺少角案例:Ifcount==0
,int-array[count];
应该避免。@chux谢谢你指出这一点。我已经对代码进行了更改,但现在范围受到限制,这是,嗯……不太好看:请添加一个解释虽然这个代码块可能会回答这个问题,但最好能提供一点解释说明为什么会这样做。如果文件由“-123 456”
,此方法将报告6。我预期为2。但OP对目标有点不清楚。@chux我同意您预期为2。OP说他想计算整数,而不是数字。感谢我编辑以解决数字问题。不过,已经有更好的解决方案了
#include <stdio.h>
int main(){
int temp;
int count = 0;
FILE *file = fopen("file1.txt","r");
if(file == NULL){
printf("Could not open specified file");
return -1;
}
while(fscanf(file,"%d",&temp)==1){
count++;
}
printf("%d",count);
if(count == 0){ //do not create array of size 0
fclose(file);
}
else{
//second run
int array[count];
rewind(file);
for(int i=0; i<count; i++){
fscanf(file,"%d",&array[count]);
}
fclose(file);
//continue using array...
}
return 0;
}
int array[0];
fscanf(file,"%d",&array[count])
#include <stdio.h>
#define isDigit(c) ('0' <= (c) && (c) <= '9') ? 1 : 0
int main() {
FILE *fd;
int counter, c, tmp;
if ((fd = fopen("PathToFile", "r")) != NULL){
do{
c = getc(fd);
if (isDigit(c)) tmp = 1;
else if (tmp == 1 && !isDigit(c)){
counter++, tmp = 0;
}
}while (c != EOF);
}else{
printf("Couldn't find File!");
return 1;
}
fclose(fd);
printf("%i", counter);
return 0;
}