-2

For example, a user enters two inputs instead of one, how do I detect that and output an error message?

1 Answers1

2

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.

Community
  • 1
  • 1
orphen
  • 66
  • 1
  • 5