0

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;
}
Hamim
  • 1
  • 2
  • The compiler isn't skipping anything (well, maybe that undefined S2 variable at the bottom of your code). Regardless, this is screaming for example input, desired output, and actual output in your question. – WhozCraig Mar 10 '16 at 08:17
  • You need to tell us what you do. What did you input to your program ? What happened ? What did you expect to happen ? Which of all these lines are the lines that the "compiler skips" ? – nos Mar 10 '16 at 08:18
  • What is `while(s1[j]!='\0')` supposed to do? It is certainly not a reliable way of iterating to the end. – stefaanv Mar 10 '16 at 08:19
  • Here is a better way to remove spaces from a string: http://stackoverflow.com/a/83538/104774 – stefaanv Mar 10 '16 at 08:26
  • sample input: s1="I am Dipto" . and i need "Iamdipto"without quotation.But i am getting nothing in output . compiler is skiping getline(cin,s1) and getline(cin,s2) lines. – Hamim Mar 10 '16 at 08:28
  • 1
    You're mixing `cin >> ...` with `getline`, see this question: http://stackoverflow.com/questions/5739937/using-getlinecin-s-after-cin – stefaanv Mar 10 '16 at 08:31

2 Answers2

0

What about j variable, it isn't set to zero when next for-loop iteration begin, so in second iteration you work with garbage.

0

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

pranav
  • 144
  • 7