0

I'm having some trouble with my second string input in my code. It works when I do it the first time, however, when I do it the second time, it skips it entirely. I copied the code the second time, but I just changed the variable name on it. Any idea's?

First time works fine

string runnerName1;
string runnerName2;

double runTime1 = 0;
double runTime2 = 0;

cout << "First Runner's Name: ";
getline(cin, runnerName1); 
cout << endl;

cout << "Finishing Time: ";
cin >> runTime1;
cout << endl;

And then I add two spaces and do it again. However, it skips the runner name string input for the second name and goes straight to the finishing time

cout << "Second Runner's Name: ";
getline(cin, runnerName2);
cout << endl;

cout << "Finishing Time: ";
cin >> runTime2;
cigien
  • 50,328
  • 7
  • 37
  • 78

1 Answers1

0

The getline() is not getting ignored by the compiler.

It is still getting executed and is reading Enter as input.

int main() {
    std::string runnerName1;
    std::string runnerName2;

    double runTime1 = 0;
    double runTime2 = 0;

    std::cout << "First Runner's Name: ";
    std::cin, runnerName1; 
    std::cout << runnerName1 << std::endl;

    std::cout << "Finishing Time1: ";
    std::cin >> runTime1;
    std::cout << runnerName1 << " - " << runTime1  << std::endl;

    std::cout << "Second Runner's Name: ";
    std::cin >> runnerName2; 
    std::cout << runnerName2 << std::endl;

    std::cout << "Finishing Time2: ";
    std::cin >> runTime2; 
    std::cout << runnerName2 << " - " << runTime2  << std::endl;

}

Other way,

std::cin.ignore() (It will discard the next available character so that the newline is no longer in the way.)

int main() {
    std::string runnerName1;
    std::string runnerName2;

    double runTime1 = 0;
    double runTime2 = 0;

    std::cout << "First Runner's Name: ";
    getline(std::cin.ignore(), runnerName1);  // cin.ignore()

    std::cout << "Finishing Time1: ";
    std::cin >> runTime1;
    std::cout << runnerName1 << " - " << runTime1  << std::endl;

    std::cout << "Second Runner's Name: ";
    getline(std::cin.ignore(), runnerName2); 

    std::cout << "Finishing Time2: ";
    std::cin >> runTime2; 
    std::cout << runnerName2 << " - " << runTime2  << std::endl;
}

Example : Code

Ivan Barayev
  • 1,845
  • 5
  • 21
  • 25