我需要从逗号分隔的 .txt 文件中读取,其中每一行看起来都是这样的:
1234,0987,Bob,23.45
(即整数、整数、字符串、 double )
使用以下设置代码:
fstream myFile;
myFile.open("textfile.txt" , ios::in);
if (myFile.is_open()) {
//read in characters as appropriate type until ','
}
我试过用
myFile >> int1 ......
但我不确定应该如何处理逗号;在读取整数时它们可能会被过滤掉,但是当我读取字符串时这会起作用吗?
我的一个同学建议使用 stringstream,但我发现 cplusplus.com 上的文档让我难以理解。
最佳答案
你可能想试试 std::getline
函数:
istream& getline ( istream& is, string& str, char delim );
istream& getline ( istream& is, string& str );
关于C++ 从格式化的 .txt 文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12103813/