Reputation: 21
I'm new to StackOverflow and I had a simple question.
I'm writing a program that accepts strings and numbers.
I used fgets
to take care of the strings part.
Summary(view previous edits if you want more gist of the problem):
As per Simone's suggestion, here is what I have so far:
int value = -1;
int check = sscanf(command, "%i%c", &value, dummy);
if (check == 1) {
sscanf(command, "%d" , &command_value);
sum = sum + command_value;
printf("Sum is now %d\n", sum);
}
else if (check == 2) {
printf("Command unrecognized.\n");
}
The problem now is that It does print out the sum but with it also prints out "command unrecognized". I think I messed up the syntax again.
Upvotes: 0
Views: 2246
Reputation: 11797
Take a look at sscanf()
, it should do the trick.
See http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/.
EDIT
Since an input value such as "12e" would have sscanf()
return 12, you could try something like this:
char dummy[1];
int value = -1;
int retv = sscanf(input_string, "%i%c", &value, dummy);
if (retv == 1) {
// input_string is a number
}
else if (retv == 2) {
// input_string is a number followed by some gibberish
}
Upvotes: 4
Reputation: 361
This bit in your (edited) question is kind of important:
"I'm not sure how I can tell it so when the user enters some numbers (eg, 12), it puts it in the running total. And if the user inputs "12e" or something, that input would be ignored."
An alternative to sscanf would be to use strtol() to check whether input ends after the numeric...
char *end;
static int running_total = 0; // static if you want a running total over repeated calls of this function...
[...]
command_value = strtol(command, end, 0);
if (end && (end != command) && *end == '\n')
running_total += command_value;
Upvotes: 1
Reputation: 29166
To get the running total -
int runningTotal = 0;
.............
// Your number input arrived
runningTotal = runningTotal + your_number_input
Upvotes: 0