For example, a user enters two inputs instead of one, how do I detect that and output an error message?
-
4Depends on which method is used to read the inputs. – πάντα ῥεῖ Oct 05 '16 at 15:27
-
And on what inputs you mean. – Rakete1111 Oct 05 '16 at 15:28
-
For example, I want one word (a string) as an input. However, the user might just enter a word, use space, then enter another word (two inputs). How do I detect the second word? I only declared one string for the first word, it doesn't store the second word. – GoodJuan Oct 05 '16 at 15:31
-
How big is your one? – seccpur Oct 05 '16 at 15:32
-
Doesn't matter, I just want to output an error message when the user enters more then one input. – GoodJuan Oct 05 '16 at 15:34
1 Answers
A user enters two inputs where?
On the command line?
Check argc
, which is the count of arguments passed to the application upon invocation.
int main(int argc, char** argv) {
// argc will always at least be 1,
// since the program name is always passed
if (argc > 3)
...
}
If you're talking about checking input elsewhere during runtime, it, as the other comments say, depends on which method you're using to read the inputs. It's hard to suggest an approach if we don't know this.
Here's an idea, based on your example you gave in your comment:
std::string str;
// take everything from stdin up to the next newline
std::getline(std::cin, str);
Now you've got the entire input string. You can split the string by spaces (many examples of that here on StackOverflow) and check that you only parsed one word. This is just an example and is not necessarily optimal, but it should point you in the right direction.
You can also use an istringstream
and just parse out the first word and discard the rest, a modification made on this StackOverflow example.