mercredi 4 janvier 2023

How to read space separated strings(lines) form cin into vector of strings in C++ [duplicate]

I have to read multiple space separated lines from cin into vector<string>. After some trial I have written this code

int main() {
    int n;
    cin >> n;
    vector<string> v(n);
    for(int i=0; i<n; i++) {
       getline(cin, v[i]);
    }
    
    cout << "==================" << endl;
    for(auto each: v) {
        cout << each << endl;
    }
} 

This reads first the number of lines I need to read into n and then creates a vector of size n and use getline to read lines. But it seems that there is a bug. Because for the first index in the vector, I get some non printable character probably \n\r and my first input goes to the second index of the vector. To get rid of this I need to create a vector of size n+1 and remove the 0th index at last. But this is not a scalable solution. Because if there are some extra new lines of some else, I would again need to adjust my vector size.

Is there any way to read strings that are space separated in c++11/14

Aucun commentaire:

Enregistrer un commentaire