Paths with fstream

Hi, I have a program in Visual C++ 2008 Express Edition to manipulate files in binary format, with the iostream library and the fstream class in a Win32 console app.

It works fine with short paths, example: c:\\test1.jpg, but when I try to use a path that includes an space, like c:\\Docume~\user\My Doc~1\test1.jpg, the console takes the string before the space as one (using cin from iostream) and the string after the space as a second entry, so the resulting path is not what I want.

This is part of the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Ini:
f_name = new char[255];
cout << "Enter file name: ";
cin >> f_name;

ifstream f_orig(f_name,ios::binary);
if(!f_orig.good())
{
   cout << "Error: The file doesn't exist" << endl;
   f_orig.close();
   cout << "\nTry another file? (y/n): ";
   cin >> f_name;
   if(f_name[0]=='y')
   {
      delete []f_name;
      goto Ini;
   }
   return 1;
}


Debugging the program, I found that cin takes an input until I press Enter or Space, in case of space when I use again cin it takes the rest of the input, an my program exits in the if sentence (line 13) before I press any key.

So, how can I introduce a path (if possible in a "complete" form like c:\\Documents and Settings\...). Thanks in advance :)
Use strings instead of cstrings and read in the input with getline: http://www.cplusplus.com/reference/string/

Also, you shouldn't be using goto for anything. There are many other ways to accomplish the same results.
Last edited on
Thanks, paths work great with strings.

Just a detail, when I used cin >> ... and getline(cin,... ) together , I think the cin instruction affects a successive getline instruction, because the program doesn't allow me to introduce characters, instead it clear the string in getline and continues the program. Is that correct?

Example:

1
2
3
4
5
6
7
8
9
...

cout << "Introduce a string: ";
cin >> char_pointer; // Saves the input characters on char_pointer pointer

cout << "Another string: ";
getline(cin,str);        // It's suposed to save the input ch. on str string, but it just clean it

...


So I replace all cin instructions for getline. Greetings
Topic archived. No new replies allowed.