从c ++中的.txt文件中读取文件

时间:2018-05-07 19:32:18

标签: c++ readfile

menu.txt的内容是:

1 Fish Dish:Fish and chips  

我的代码是:

int itemNo;
string category;
string descript;

ifstream infile("menu.txt"); 
infile >> itemNo >> category >> descript;
cout << category  << " - " << descript << " - " << itemNo <<'\n';

我想得到:

Fish Dish - Fish and chips - 1

但出于某种原因,我得到:

Fish - Dish:Fish - 1

1 个答案:

答案 0 :(得分:0)

您可以将分隔符更改为冒号。见this answer for more information

或者更简单的方法是使用getline()函数:

istream& getline (istream& is, string& str, char delim)

所以,举个例子:

int itemNo;
string category;
string descript;

ifstream infile("menu.txt");
infile >> itemNo;
getline(infile, category, ':');
getline(infile, descript);
cout << category  << " - " << descript << " - " << itemNo <<'\n';

这将给出:

 Fish Dish - Fish and chips - 1

要摆脱Fish Dish开头的额外空间,请添加额外的getline。

int itemNo;
string category;
string descript;

ifstream infile("menu.txt");
infile >> itemNo;
getline(infile, category, ' ');
getline(infile, category, ':');
getline(infile, descript);
cout << category  << " - " << descript << " - " << itemNo <<'\n';