从文件 C++ 中读取字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20902945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:23:16  来源:igfitidea点击:

Reading a string from file c++

c++stringfile-handling

提问by user3139551

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.

我正在尝试为我父亲的餐厅制作计费系统,只是为了练习。所以,我面临着一次无法读取完整字符串的问题。例如,如果txt 文件中有Chicken burger,编译器会读取它们,但将它们分成两个词。我正在使用以下代码并且该文件已经存在。

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

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

回答by Mike Seymour

To read a whole line, use

要阅读整行,请使用

std::getline(nameFileout, item_name)

rather than

而不是

nameFileout >> item_name

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

您可能会考虑重命名,nameFileout因为它不是名称,并且用于输入而不是输出。

回答by utnapistim

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)
}