简体   繁体   中英

How to take input of a string with whitespace in c++

Why I can't take inputs of a string using gets,getline and cin.getline.when I debugg it seems that compiler skips those lines.here's my code-

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string s1,s2;
    char *p;
    int n,m,i;
    cin>>n;
    for(i=1;i<=n;i++)
    {
        int j=0;
        getline (cin,s1);
        getline (cin,s2);
        cout<<s1<<"\n";
        while(s1[j]!='\0')
        {
            if(s1[j]==' ')
            {

                s1.erase(s1[j]);

            }
            j++;
        }

    }
    cout<<s1<<S2<<endl;
    return 0;
}

那么j变量呢,下一次for循环迭代开始时它不会设置为零 ,因此在第二个迭代中,您将使用垃圾

Every time you use cin , it stores every character entered in memory until it encounters a newline character. This block of memory is called the input buffer. when you take the input for 'n' the return key is in the cin buffer.

You should use cin.ignore to get rid of this newline.

Before getline (cin,s1); add cin.ignore statement

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