Question

How do I get rid of the leading ' ' and '\n' symbols when I'm not sure I'll get a cin, before the getline?

Example:

int a;
char s[1001];
if(rand() == 1){
    cin >> a;
}

cin.getline(s);

If I put a cin.ignore() before the getline, I may lose the first symbol of the string, so is my only option to put it after every use of 'cin >>' ? Because that's not very efficient way to do it when you are working on a big project.

Is there a better way than this:

int a;
string s;

if(rand() == 1){
    cin >> a;
}

do getline(cin, s); while(s == "");
Was it helpful?

Solution

Like this:

std::string line, maybe_an_int;

if (rand() == 1)
{
    if (!(std::getline(std::cin, maybe_an_int))
    {
        std::exit(EXIT_FAILURE);
    }
}

if (!(std::getline(std::cin, line))
{
    std::exit(EXIT_FAILURE);
}

int a = std::stoi(maybe_an_int);    // this may throw an exception

You can parse the string maybe_an_int in several different ways. You could also use std::strtol, or a string stream (under the same condition as the first if block):

    std::istringstream iss(maybe_an_int);
    int a;
    if (!(iss >> a >> std::ws) || iss.get() != EOF)
    {
        std::exit(EXIT_FAILURE);
    }

You could of course handle parsing errors more gracefully, e.g. by running the entire thing in a loop until the user inputs valid data.

OTHER TIPS

Both the space character and the newline character are classified as whitespace by standard IOStreams. If you are mixing formatted I/O with unformatted I/O and you need to clear the stream of residual whitespace, use the std::ws manipulator:

if (std::getline(std::cin >> std::ws, s) {

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top