Reputation: 2795
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.
Upvotes: 0
Views: 99
Reputation: 4962
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.
Upvotes: 1
Reputation: 103703
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);
Upvotes: 1
Reputation: 3766
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.
Upvotes: 0