I am making an app that records the time, userID, and weight. How can I check if the first token passed is an integer? I thought I would use isdigit, but that just works for single chars. I want to output Invalid time if the first token is not an integer. I'm currently using
sscanf(userInput, "%d %s %f", ×tamp, userID, &weight);
If the first token is not an integer (has alphabets for example) I still get a number for the variable timestamp,, which I don't want.
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;
}
}
foo = printf('%d %s, %f', the, values, here); if (!strcmp(foo, userinput)) { ruh_roh(); }sscanf()to determine how many parameters were successfully parsed. Heed the Sixth Commandmentisdigitfor your timestamp or withisalphafor your ID. (Better write functions for that.) Or you could read the time in as string in your firstsscanfand then runsscanf(..., "%d", ...)` on that string.