sscanf
函数有问题。更具体地说,我想从一个 txt 文件中读取一个 float (我只想要一个 float )但是 sscanf
无法识别这些情况:
3.4t
或
4.t6
或
4.5 6.5
或
(this is an empty line)
我使用这段代码:
#define LUNRIGA 200
char riga[LUNRIGA+1];
while (fgets(riga,LUNRIGA,f) != NULL) {
r = sscanf(riga,"%f",&numeri[i]);
if (r == 1) { /* riga valida */
printf("OK");
}else{
printf("Error");
return 1;
}
}
最佳答案
sscanf
对输入非常挑剔。使用 strtod
或 strtol
时你会更幸运——它们可以读取一个值,即使它后面是垃圾。按如下方式更改您的代码:
#define LUNRIGA 200
char riga[LUNRIGA+1];
char* tempPtr;
while (fgets(riga,LUNRIGA,f) != NULL) {
numeri[i] = strtof( riga, &tempPtr );
if (tempPtr > riga) { /* riga valida */
printf("OK");
}
else {
printf("Error");
return 1;
}
}
请注意,您似乎没有在循环中递增 i
- 您可能想看看这是否真的是您想要的,或者您是否想每次都递增它得到一个有效的数字(假设你不只是想要最后一个值,而是所有的......)
作为 strtod
行为的一个小演示,我写了几行代码:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char* s1="123.45t";
char* p1;
char* s2 = " notanumber";
double d1, d2;
d1 = strtod(s1, &p1);
printf("the number is %.2lf; the pointer is now %p; string is at %p\n", d1, s1, p1);
d2 = strtod(s2, &p1);
printf("the number is %.2lf; the pointer is now %p; string is at %p\n", d2, s2, p1);
}
这个的输出是:
The number is 123.45; the pointer is now 0x400668; string is at 0x40066e
The number is 0.00; the pointer is now 0x400670; string is at 0x400670
如您所见,当读取垃圾时,返回的指针指向字符串的开头 - 指示“失败”。当它成功时,指针指向“我停止阅读的地方”,即“在成功地将一个字符串转换为 double 之后”。
关于c - sscanf 和正确的格式文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17576481/