简体   繁体   中英

Getline & cin.ignore in c++

I know there are similar questions to mine, but I checked alot of them and didn't find the answer so I hope someone can help me. So what I am trying to do is store some strings into arrays, but some of these strings could consist of more than one word, so I searched the internet and found out I have to use cin.ignore() and Getline. I used them, as seen in my code below, but the error happens in the second and third string where the first letter of surname[0] and address[0] is removed. So why is that? Thanks

Here is my code:

    int size;
    cout<<"Please enter the number of entries"<<endl;
    cin>>size;
    cin.ignore();
    string* firstname=new string[size];
    string* surname=new string[size];
    string* address=new string[size];
    cout<<"First Name"<<endl;
    for (int i=0;i<size;i++)
        getline (cin, firstname[i]);
    cout<<"Surname"<<endl;
    cin.ignore();
    for (int i=0;i<size;i++)
        getline (cin, surname[i]);
    cout<<"Address"<<endl;
    cin.ignore();
    for (int i=0;i<size;i++)
        getline (cin, address[i]);
    for (int i=0;i<size;i++)
    {
        cout<<"First Name "<<firstname[i]<<endl;
        cout<<"Surname "<<surname[i]<<endl;
        cout<<"Age "<<address[i]<<endl;
    }

EDIT: Sample Input/Output

Please enter the number of entries

4

First Name

John

Michael

Daniel

Radu

Surname

Laaksonen

Taro

Albot

Smith

Address

123 Larkin Street

900 Larkin Street

823 Larkin Street

283 Larkin Street

**First Name John

Surname aaksonen

Address 23 Larkin Street

First Name Michael

Surname Taro

Address 900 Larkin Street

First Name Daniel

Surname Albot

Address 823 Larkin Street

First Name Radu

Surname Smith

Address 283 Larkin Street**

Bold is the program's output. See how the L in Laaksonen is missing and the 1 in 123 is missing.

getline() reads and discard delimiter ( reference ), you have to use cin.ignore() only when you read your first integer:

cout<<"First Name"<<endl;
for (int i=0;i<size;i++)
    getline (cin, firstname[i]);

cout<<"Surname"<<endl;
// Remove this: cin.ignore();
for (int i=0;i<size;i++)
    getline (cin, surname[i]);

cout<<"Address"<<endl;
// Remove this: cin.ignore();
for (int i=0;i<size;i++)
    getline (cin, address[i]);

That said you may avoid standard arrays, a std::vector<std::string>> firstNames would be more appropriate.

一种替代方法是使用getline()读取全部内容,然后自己解析整数(使用atoi或类似的方法),而无需完全忽略。

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