我需要在读取文本文件的搜索二叉树中插入数据。当我在数据之间使用空格时它起作用,但如果我像我想的那样使用逗号它不起作用。 例如,我希望我的文本文件看起来像这样:
New-York,c3,Luke
London,c5,Nathan
Toronto,c1,Jacob
...
我的文本文件现在看起来像这样:
New-York c3 Luke
London c5 Nathan
Toronto c1 Jacob
...
我还希望我的程序不认为空格意味着它需要查看下一个数据,只能使用逗号。
我的代码是这样的:
void fillTree( BinarySearchTree *b)
{
ifstream file;
file.open("data.txt");
string city;
string tag;
string name;
Person p;
if(!file) {
cout<<"Error. " << endl;
}
while(file >> city >> tag >> name)
{
p.setCity(city);
p.setTag(tag);
p.setName(name);
cout << p.getCity() << " " << p.getTag() << " " << p.getName() << endl;
(*b).insert(p);
}
file.close();
}
我需要在我的代码中更改什么才能使用逗号而不是空格?我觉得在文本文件中用逗号而不是空格看起来会更整洁。 我很确定我需要在此代码块中编辑某些内容,但如果它可以在其他地方,请告诉我。
最佳答案
使用 getline ( file, value, ',' );
读取字符串直到出现昏迷。
string value;
while(file.good())
{
getline ( file, value, ',' );
p.setCity(value);
getline ( file, value, ',' );
p.setTag(value);
getline ( file, value, ',' );
p.setName(value);
cout << p.getCity() << " " << p.getTag() << " " << p.getName() << endl;
(*b).insert(p);
}
关于c++ - 我的程序需要读取一个文本文件,文本文件中的数据需要用逗号分隔(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13443592/