How to get both a line and an integer in a program?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mohamad mahtabi
    New Member
    • Jan 2011
    • 3

    How to get both a line and an integer in a program?

    I don't know how can I get both a line and an integer in a program

    for example take a look at this simple code:
    Code:
    string s;
    int x;
    cin >> x;
    getline( cin , s );
    cout<< s << x ;
    the program ignores the getline.
    how can I solve the problem?
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    what happens is the '\n' <RETUIRN> character entered after you entered the value of x is left in the input stream and read by the getline() as string s.
    you need to remove the '\n', e.g. use cin.ignore()
    Code:
    cin >> x;
    std::cin.ignore(1000, '\n');
    getline( cin , s );
    the cin.ignore() will read up to a 1000 characters or until '\n' is found and extract them.

    Comment

    • mohamad mahtabi
      New Member
      • Jan 2011
      • 3

      #3
      thank you a lot.

      Comment

      Working...