Reading a string from file c++

隐身守侯 提交于 2019-11-27 04:43:06

问题


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();

回答1:


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.




回答2:


Read line by line and process lines internally:

string item_name;
ifstream nameFileout;
nameFileout.open("name2.txt");
string line;
while(std::getline(nameFileout, line))
{
    std::cout << "line:" << line << std::endl;
    // TODO: assign item_name based on line (or if the entire line is 
    // the item name, replace line with item_name in the code above)
}


来源:https://stackoverflow.com/questions/20902945/reading-a-string-from-file-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!