Deepesh Thapa
Deepesh Thapa

Reputation: 1789

Unable to read Char/string in loop

This is a very simple problem that has been bothering me a lot. While reading a character from a line in a while loop, it does not read the second time. If I use cin>>name it works fine, but I need spaces between characters. Same problem using String class.

int main()
{
    int i=0;
    int intRate;
    char name[20];
    while(i!=3){
        cout<<"Enter name";
        gets(name);

        cout<<"Enter Interest Rate: ";
        cin>>intRate;

        i++;
        cout<<endl;
    }
    cout<<"name is : "<<name<<endl;
    cout<<"Interest Rate is: " <<intRate;
}

So, when I try to type the character "gets(name)" in the loop, the first time it accepts the character and then I can also enter the intRate, but next time when I come across loop i=1 I cannot type anything for name, or it does not read any character line but instead prints Enter Interest Rate and it read the intRate in the following loops.

But if I don't put the enter interest rate line then it starts reading smoothly again, like below:

char name[20];
while(i!=3){
    cout<<"Enter name";
    i++;
    cout<<endl;

If I do this, it reads all the characters from the loop. And if I add another print line below it, it just does not read anything.

Upvotes: 0

Views: 324

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595367

This is what happens when you mix C and C++ input and don't pay attention to what they are actually doing.

Try this instead:

int main()
{
    int i = 0;
    int intRate = 0;
    string name;
    while (i != 3)
    {
        cout << "Enter name: ";
        getline(cin, name);

        cout << "Enter Interest Rate: ";
        cin >> intRate;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');

        i++;
        cout << endl;
    }

    cout << "Name is : " << name << endl;
    cout << "Interest Rate is: " << intRate;

    return 0;
}

Or this:

int main()
{
    int i = 0;
    int intRate = 0;
    string name, line;
    while (i != 3)
    {
        cout << "Enter name: ";
        getline(cin, name);

        cout << "Enter Interest Rate: ";
        getline(cin, line);

        stringstream ss(line);
        ss >> intRate;

        i++;
        cout << endl;
    }

    cout << "Name is : " << name << endl;
    cout << "Interest Rate is: " << intRate;

    return 0;
}

Upvotes: 1

Related Questions