我编写此代码以从文本文件中读取以下行: 1019 * /通过// 56.)100,/ 82 // 10但是当我打印它时,我只能获得1019和10号正确的数据,其余的有垃圾值,任何想法为什么?如果有人可以纠正我,我会很感激,我甚至尝试在sscanf函数中输入%d而不是%[..],但是stil没有打印出所需的值。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char buffer[100];
char status[20];
int grades[4]= {0};
int id;
int j;
int k;
int temp;
FILE *pointer = fopen ("testing5.txt", "r");
if((pointer = fopen("testing5.txt", "r"))!= NULL)
{
printf("No error, file successfully opened\n you may contine :)\n");
}
else
{printf("file could not be opened\nterminating program,...\n");
return 0;}
fgets(buffer,100,pointer);
printf("%s\n", buffer);
sscanf(buffer,"%[^*/]*/%[^//]//%[^.).)]%[^,/],/ %[^//]//%d",&id,status, &grades[0],&grades[1],&grades[2],&grades[3]);
printf("%d\n%s\n%d\n%d\n%d\n%d",id,status, grades[0],grades[1],grades[2],grades[3]);
for (j =0; j<3; j++)
for(k =j+1; k<4;k++)
{
if(grades[j]<grades[k] )
{
temp = grades[j];
grades[j] = grades[k];
grades[k] = temp;
}
}
printf("\nthe grades in ascending order is \n");
for (j =0; j<4; j++)
{
printf("%d\n", grades[j]);
}
return 0;
}
答案 0 :(得分:0)
sscanf("1019*/passed// 56.)100,/ 82//10\n", "%d*/%[^/]// %d.)%d,/ %d//%d",
&id, status, &grades[0],&grades[1],&grades[2],&grades[3]);
答案 1 :(得分:0)
更改
int grades[4]= {0}
到
char grades[4] = { 0 };
警告输出指出问题,不要忽略它。您将错误的数据类型传递给sscanf。