C++ skips line when promting for user to enter name of person being added to a string array

57 Views Asked by At

ran the program more than once and this error occurred, wondering if its something i did wrong?? Please take a look at the code if u know c++. I am a beginner but I'm trying to learn fast because I'm signing up for computer science this year. Thanks

#include<iostream>
#include<string>

using namespace std;


int main() {

    // Create a string array
    string* names = new string[10];
    for (int i=0; i<10; i++) {
        cout << "Person (" << i+1 << ") Enter name: " << endl;
        cin >> names[i];
    }
    
    // Print the string array with welcome message

    cout << "Welcome guests:" << endl;
    for (int i=0; i<10; i++) {
        cout << names[i] << endl;
    }

    return 0;
}

I mentioned I tried to run the program more than once and cannot find the error either.

1

There are 1 best solutions below

1
Rohan Bari On

As mentioned in one of the comments, the std::cin ceases to take further input as soon as a space is encountered. The skipping is only possible if you input first and surnames, which needs a space letter in between. In that case, consider taking the help of a function std::getline.

Here is the remedy you have to apply:

// Change this line: cin >> names[i];
// To the following:
std::getline(std::cin, names[i]);

Then you are good to go.