【发布时间】:2014-01-21 18:20:13
【问题描述】:
我正在制作一个记录时间、用户 ID 和体重的应用程序。如何检查传递的第一个令牌是否为整数?我以为我会使用 isdigit,但这仅适用于单个字符。如果第一个标记不是整数,我想输出无效时间。我目前正在使用
sscanf(userInput, "%d %s %f", ×tamp, userID, &weight);
如果第一个标记不是整数(例如有字母),我仍然会得到变量时间戳的数字,这是我不想要的。
int main()
{
char userInput[99];
int timestamp, timestampT = 0;
char userID[31];
userID[0] = 0;
float weight, weightT, day, rateW;
while(fgets(userInput, 99, stdin) != NULL){
sscanf(userInput, "%d %s %f", ×tamp, userID, &weight);
if(timestamp == 0 ){
printf("%s\n", "Invalid time");
}
else if(!isalpha(userID[0]) || userID[0]=='_' || userID[0] == 0){
printf("%s\n", "Illegal userID");
}
else if(weight < 30.0 || weight > 300.0){
printf("%s\n", "Illegal weight");
}
else if(timestampT > 0){
day = timestampT/86400;
rateW = (weightT -weight)/(day - timestamp/86400);
if(rateW > 10.0 || rateW < -10.0){
printf("%s\n", "Suspiciously large weight change");
}
}
else{
printf("%d %s %f \n", timestamp, userID, weight);
timestampT = timestamp;
timestamp = 0;
weightT = weight;
}
userID[0] = 0;
}
}
【问题讨论】:
-
使用 sscanf 的结果构建另一个字符串,然后将原始字符串与重建字符串进行比较。如果它们不同,那么某些东西没有正确转换。例如
foo = printf('%d %s, %f', the, values, here); if (!strcmp(foo, userinput)) { ruh_roh(); } -
首先使用
sscanf()的结果来确定成功解析了多少参数。 Heed the Sixth Commandment -
您可以使用
isdigit作为您的时间戳或使用isalpha作为您的ID 检查字符串的所有字符。 (最好为此编写函数。)或者您可以在第一个sscanf中将时间作为字符串读取,然后在该字符串上运行sscanf(..., "%d", ...)`。