Jamal Hussain
Jamal Hussain

Reputation: 51

C++ string input using functions

I have wrote a code for taking string from the user in C++. here is the code

#include<iostream>
#include<string>
using namespace std;
string input;
void enterstring()
{
    cout<<"\nEnter input: ";
    getline(cin,input);

}
void displaystring()
{
    cout<<"\nyour string is "<<input<<endl;

}
{
    int main()
{
int choice=0;
while(choice!=3)
{

    cout<<"Enter choice: "<<;
          cin>>choice;
    switch(choice)
    {
        case 1: enterstring();
        break;
        case 2: displaystring();
        break;
        case 3: cout<<"\nQuit";
        break;
        default: cout<<"\ninvalid choice try again";
        break;


    }
    return 0;
}

output of the above code:

Enter choice: 1
Enter input: 
Enter choice:

the input section is skipped I don't know why where is the problem. Is the logic wrong, problem with syntax anything. when I call function without using while loop etc it's working fine but in this case it's not working. help me.

Upvotes: 3

Views: 9984

Answers (2)

pinco
pinco

Reputation: 891

The problem is that you are reading choice as int but the input is a string with a newline.

In your example the input is not 1 is "1\n" 1 goes in choice as int, '\n' is in the buffer. When you call the getline function that function read from the buffer, found the newline and return an empty string. To avoid that you should read choice as string and than use atoi to cast to int.

EDIT:

you are right. It's still not working. But here there is a version that work.

#include <iostream>
#include <string>

using namespace std;
string input;
void enterstring(){
    cout<<"\nEnter input: ";
    cin.ignore();
    getline(cin,input);
}

void displaystring(){
    cout<<"\nyour string is "<<input<<endl;
}

int main(){
    int choice=0;
    while(choice!=3){
        cout<<"Enter choice: ";
        cin>>choice;
        switch(choice){
            case 1: enterstring();
            break;
            case 2: displaystring();
            break;
            case 3: cout<<"\nQuit";
            break;
            default: cout<<"\ninvalid choice try again";
            break;
        }
    }
    return 0;
}

Upvotes: 3

alestanis
alestanis

Reputation: 21863

The code you posted is invalid: you are missing a " after Enter choice :.

Besides from that, your code seems to work in ideone (I added some indentation and corrected some small bugs. I also added a main function). You can see it here : http://ideone.com/ozvB1

Upvotes: 1

Related Questions