正确使用sscanf解析字符串c++
Proper use of sscanf to parse string c++
缓冲区中的文本:
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
目的地是正确的号码,而起点不是。我该如何解决这个问题?
我在您发布的代码中看不到任何错误。最好添加代码来执行错误检查。然后你可以看到问题出在哪里。
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 buffern");
}
}
else
{
printf("Unable to read the text for sourcen");
}
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 buffern");
}
}
else
{
printf("Unable to read the text for destinationn");
}