0

I am trying to read a line from a file that has spaces in it. Despite everything I've tried and all my research, nothing seems to work, here is my current attemp

void read_name(fstream& in_file, comp& cmp)
{
   char buff[80];
   in_file.getline(buff, 79, '\n');
   in_file >> buff;

   cout << "NAME: " << buff << endl;

   cmp.set_name(buff);
   in_file.getline(buff, 79);
}

For whatever reason, this will still read until it sees a space and then stops. Any help would be much appreciated. I'm not that great with straight C++ so I could very well just be missing something.

roundtheworld
  • 2,651
  • 4
  • 32
  • 51

3 Answers3

1
in_file.getline(buff, 79, '\n');

There. You read a line (assuming the line wasn't longer than 78 characters). So why'd you go and do this?

in_file >> buff;

That's going to overwrite the line you just read with the next word. If you want the next line, then call getline again.

But it's better to use std::string and the free function std::getline, that way you don't have to specify line lengths.

std::string buff;
std::getline(in_file, buff);
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • I tried this, but it doesn't print out anything after "NAME:" void read_name(fstream& in_file, comp& cmp) { std::string line; if (std::getline(in_file, line)) { cout << "NAME: " << line << endl; } cmp.set_name(buff); in_file.getline(buff, 79); } – roundtheworld Mar 22 '13 at 19:00
  • @user1595510: Then something else is going wrong, perhaps the contents of the file aren't what you expect, I don't know. I can't diagnose it without more information. http://sscce.org/ – Benjamin Lindley Mar 22 '13 at 19:07
1

The line

in_file >> buff;

is wiping out the contents of buff which you've just read from the file. If you step through your code with a debugger watching the contents of buff then you would see this happening.

Rich
  • 4,572
  • 3
  • 25
  • 31
0

Since you are using c++ I recommend you use stl string instead of char arrays.

std::string linestr;
while( std::getline(input, linestr) )
{
   // process line
}

where input is your ifstream.

DiegoNolan
  • 3,766
  • 1
  • 22
  • 26
  • 1
    And since we're using standard C++, I recommend you call the C++ standard library "the C++ standard library", and not "STL" which it isn't. –  Mar 22 '13 at 18:57