Reading a string from file c++

user3139551 picture user3139551 · Jan 3, 2014 · Viewed 65.6k times · Source

I'm trying to make billing system for my father's restaurant just for practice. So, I'm facing the problem that I can't be able to read the complete string one time.e.g If there were Chicken burger in txt file than compiler read them but break them into two words. I'm using the following code and the file is already exist.

std::string item_name;
std::ifstream nameFileout;

nameFileout.open("name2.txt");
while (nameFileout >> item_name)
{
    std::cout << item_name;
}
nameFileout.close();

Answer

Mike Seymour picture Mike Seymour · Jan 3, 2014

To read a whole line, use

std::getline(nameFileout, item_name)

rather than

nameFileout >> item_name

You might consider renaming nameFileout since it isn't a name, and is for input not output.