如何使用fscanf
(或任何其他处理来自文本文件的stdin
的函数)来扫描具有相同长度的某组整数,并将它们放入相同的数组,但同时忽略短于所需的整数
这是txt文件的外观:
63001234 1 1 -1 - - 0 1 1 1 - - 0
63001230 1 1 1 1 1 1 1 1 1 1 1 1
63001432 -1 -1 - - - - - - - - - -
63000176 - - 1 0 0 1 0 0 1 1 1 1
我需要将63 ...数字存储在一个int数组中,' 1',' -1',' 0'和' - '在另一个char数组中。
现在我的扫描和测试功能在一个
中int main() {
printf("insert the name of the txt file you want to scan from: ");
char fileopen [100];
scanf("%s", fileopen);
int Students [250];
char Grades [250] [12];
FILE *fop = fopen(fileopen ,"r");
if(fop == NULL){
printf("Error");
EXIT_FAILURE;
}
int counter = 0;
//read file
while(1){
if(fscanf(fop,"%d",&Students[counter]) == EOF){
break;
}
for(int j = 0; j < 12; j++){
fscanf(fop," %c",&Grades[counter][j]);
}
fscanf(fop,"\n");
counter++;
}
counter = 0;
//test what has been written in the arrays
while(counter <= strlen(Students)){
printf("%d", Students[counter]);
for(int j = 0; j < 12; j++){
printf(" %c", Grades[counter][j]);
}
counter++;
printf("\n");
}
}
答案 0 :(得分:0)
您可以直接读取整数和字符而不是使用数字检查:
// You can use dynamic memory allocation here instead, or an appropriate max size.
// I used 100 because this is a template.
int numbers[100];
int chars[100][12];
char* line = (char*)malloc(100);
int i = 0;
while (true)
{
/* Read line into buffer */
if ((fgets(line, 100, file) == NULL) || ferror(file) || feof(file))
{
break;
}
/* Skip empty lines */
if (strcmp(line, "\n") != 0)
{
continue;
}
/* Scan the integer */
if (i == 0) {
sscanf(line, "%d", &numbers[0]);
} else {
sscanf(line, "\n%d", &numbers[i]);
}
/* Scan the 12 characters */
for (unsigned int j = 0; j < 12; ++j)
{
sscanf(line, " %c", &chars[i][j]);
}
i++;
}