Archived

This topic is now archived and is closed to further replies.

NewbJ

cin and cin.getline()

Recommended Posts

NewbJ    226
I need to get a file path from the user in a program I''m writing, so I was using cin.getline() with a character string to get it. This worked just fine until I moved the block of code into another function. Now, the program simply skips the cin.getline() altogether the first time it reaches it. If I use just plain cin, it works, but it will not take spaces, which becomes a problem. Though I''m not sure it will do any good, here''s the block of code in question:
   int flag = 0;
  while (flag == 0)
  {
    cout << "What is the file path?: ";
    char path[50];
    cin.getline(path, 50);

    fstream file;
    file.open (path, ios::in);

    if ( file.is_open() ) //if the file is opened successfully...

    {
      flag = 1;  //make it so that the while loop doesn''t repeat

      filePath = path;
    }
    if ( ! file.is_open() )
    {
      cout << "That file could not be opened!\n"
           << "Please check the path and try again.\n\n";
    }

    file.close();
  }
Basically, this is just getting a file path, making sure that it is good, and if it isn''t repeating the process. When I go through it the first time, however, it skips directly to the output of "That file could not be opened!", but when it repeats it acts normally. I am including the iostream and fstream headers. Any suggestions? Thanks!

Share this post


Link to post
Share on other sites
Oluseyi    2103
VC6 by any chance? The STL implementation supplied with that version of MSVC is buggy; find fixes here.

After fixing, see if the condition persists. Then we''ll know it''s in your source.

Share this post


Link to post
Share on other sites
aftermath    100
Instead of doing all of these fixes to the borked Microsoft VC 6 STL implementation, I suggest you get STLport - an alternative and widely used implementation of the Standard Template Library that is, well “better” then the one that comes standard with MSVC 6. However, note that the STL implementation that comes with MSVC .NET is _said_ to be better/faster then STLport, but then again it could be something propertary (not a surprise coming out of Microsoft.)

Share this post


Link to post
Share on other sites
_Twiggie_    122
Try adding a std::cin.ignore( ) call before or after your getline statement (I dont remember where exactly). This has fixed similar sounding issues in the past.

[edited by - _Twiggie_ on March 23, 2004 5:30:36 PM]

Share this post


Link to post
Share on other sites
NewbJ    226
Thanks everyone...I''m actually using Dev-C++, but that bug may still apply.

Anyways, putting cin.ignore() before the cin.getline() statement solved the problem. I don''t know the reason that it helps, but I guess I can research that on my own.

Share this post


Link to post
Share on other sites