Question

I'm supposed to force the user to input a number then a space then a string and if the format was wrong, I should terminate the program. When I used the cin, the compiler ignored the space and considered the first character of the string to be the one he should check to make sure that the user inputs a space and since the first character is always not a space he terminates. What should I do ?!

Was it helpful?

Solution

I assume by "when I used the cin" you mean with the >> operator. Reading from an istream with >> is a formatted input function which means the input is pre-formatted for you, one of the effects is skipping over whitespace by default.

There are several ways to solve your problem, including reading a single character at a time (using an unformatted input function such as std::istream::get) or reading a line at a time and parsing the line.

Alternatively, you can turn off skipping of whitespace characters with the noskipws manipulator:

#include <iostream>
#include <string>

int main()
{
  int num;
  char c;
  std::string str;
  if (std::cin >> std::noskipws >> num >> c >> str && c == ' ')
    std::cout << "ok" << std::endl;
  else
    std::cout << "Failed" << std::endl;
}

OTHER TIPS

Use std::getline. If you require further help, make sure to post a code sample which demonstrates the problem, otherwise you won't get specific answers.

Example:

#include <string>
#include <iostream>

int main()
{
    std::string input;
    std::cout << "Please enter a number and a string, separated by a space:";
    std::getline(std::cin, input);
    // Code to validate input
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top