简体   繁体   中英

Why doesn't read 2 strings?

using namespace std;
#include <iostream>
#include <cstring>
#include <string>

int main()
{
    int k;
    cout << "inserisci k: ";
    cin >> k;
    string stringa1;//nb
    string stringa2;//m

    cout<<"inserisci nb:";
    getline(cin, stringa1);

    cout<<"inserisci m:";
    getline(cin, stringa2);

    cout<<"nb: "<<stringa1<<endl;
    cout<<"m: "<<stringa2<<endl;

}

hi, i'd like to read string like "nb m1 m2... mn" but i don't understand because my code doesn't work. lines

cout<<"inserisci nb:";
getline(cin, stringa1);

don't work but

cout<<"inserisci m:";
getline(cin, stringa2);

work perfectly. can you help me? thanks.

Following syntax of getline :

std::getline(std::cin, str, 's');

It accepts a third argument as the character at which it will stop. Although optional, it matters here because std::cin leaves a newline character \n .

Use cin.ignore() , since if getline() is not provided with a character to stop (as the third argument), it will stop when it reaches a newline.

    cout<<"inserisci nb:";
    getline(cin.ignore(), stringa1);

    cout<<"inserisci m:";
    getline(cin.ignore(), stringa2);

After the cin to read k , it leaves a newline character.

But getline stops reading input after seeing that newline character. So you would need to remove that \n . One way is to call before the first getline call:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

(Need to include <limits> header).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM