CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Dec 2004
    Location
    Paso de Robles
    Posts
    296

    Skipping right over getline

    Code:
    #ifdef HAVE_CONFIG_H
    #include <config.h>
    #endif
    
    #include <iostream>
    #include <cstdlib>
    
    using namespace std;
    
    bool yes()
    {
      string ans;
      while (true)
      {
    	cin >> ans;
    	if ( (ans == "Y") || (ans == "y") )
    	  return true;
    	if ( ans == "N" || ans == "n" )
    	  return false;
    	if (ans == "Q" || ans == "q" )
    	  exit(0);
    	cout << "Invalid option" << endl;
      }
    }
    
    
    int main(int argc, char *argv[])
    {
      string file;
      file = "Hello, world";
      cout << "Rename file to: " << file << endl;
      if (!yes())
    	 getline(cin, file);
      cout << file;
    
      return EXIT_SUCCESS;
    }
    The output for this looks like this:
    Rename file to: Hello, world
    n
    Press Enter to continue!
    For some reason it skips right over getline. Any idea of why this is happening?

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: Skipping right over getline

    Mixing operator >> and getline() is a bit tricky. In yes() ypu do a

    Code:
    cin >> ans;
    This stops reading from the stream when it sees a whitespace in
    the stream. The important point is that the position of the stream
    is just before that whitespace (in your case the whitespace will be '\n').

    Next in main you do a
    Code:
    getline(cin, file);
    This starts reading at the current stream position until it reaches a '\n'.
    However the current stream position is a '\n'.

    One way to get around this is to throw out everything in the stream
    after doing the operator >>

    Code:
      if (!yes())
      {
        // skip until end-of-line
         cin.ignore(std::numeric_limits<int>::max(),'\n');  // include <limits>
    
         getline(cin, file);
      }
    (also, in your code you forgot to include <string>)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured