简体   繁体   English

从格式化的.txt文件读取C ++

[英]C++ read from formatted .txt file

I need to read in from a comma-separated .txt file where each line looks something this: 我需要从逗号分隔的.txt文件中读取内容,其中每行看起来都是这样的:

1234,0987,Bob,23.45 1234,0987,Bob,23.45

(ie int,int,string,double) (即int,int,string,double)

using the following setup code: 使用以下安装代码:

fstream myFile;
myFile.open("textfile.txt" , ios::in);
if (myFile.is_open()) {
    //read in characters as appropriate type until ','
}

I have tried using 我尝试使用

myFile >> int1 ......

but I was unsure how I should deal with the commas; 但是我不确定如何处理逗号。 they may get filtered out when reading in integers, but would that work when I get to the string? 当读取整数时,它们可能会被过滤掉,但是当我到达字符串时,这行得通吗?

one of my classmates suggested stringstream, but i've found the documentation on cplusplus.com to be over my head. 我的一位同学建议使用stringstream,但是我发现cplusplus.com上的文档很麻烦。

You might want to try out the std::getline function: 您可能想尝试一下std::getline函数:

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

(From http://www.cplusplus.com/reference/string/getline/ ) (来自http://www.cplusplus.com/reference/string/getline/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM