缓冲区中的文字:
Source$1
Destination$5
代码:
char buffer[50];
int start = 0;
int dest = 0;
FILE * infile = fopen(argv[1], "r")
fgets(buffer, sizeof(buffer), infile);
sscanf(buffer, "Source$%d", &start);
printf("start: %d \n", start);
fgets(buffer, sizeof(buffer), infile);
sscanf(buffer, "Destination$%d", &dest);
printf("destination: %d \n", dest);
输出:
start: 0
destination: 5
目的地是正确的号码,开始不是。 我该如何解决这个问题?
答案 0 :(得分:2)
我发布的代码中没有任何错误。最好添加代码来执行错误检查。然后你可以看到问题所在。
if ( fgets(buffer, sizeof(buffer), infile) )
{
printf("%s", buffer);
if ( sscanf(buffer, "Source$%d", &start) == 1 )
{
printf("start: %d \n", start);
}
else
{
printf("Unable to read source from buffer\n");
}
}
else
{
printf("Unable to read the text for source\n");
}
if ( fgets(buffer, sizeof(buffer), infile) )
{
printf("%s", buffer);
if ( sscanf(buffer, "Destination$%d", &dest) == 1 )
{
printf("destination: %d \n", dest);
}
else
{
printf("Unable to read destination from buffer\n");
}
}
else
{
printf("Unable to read the text for destination\n");
}