【问题标题】:C++ read from formatted .txt fileC++ 从格式化的 .txt 文件中读取
【发布时间】:2012-08-24 05:53:08
【问题描述】:

我需要从逗号分隔的 .txt 文件中读取,其中每一行看起来像这样:

1234,0987,鲍勃,23.45

(即int,int,string,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 采用分隔符。你可以玩那个。这可能不是我能想到的最优雅的方法,但对于“C++ 新手”来说,应该可以玩弄。
  • 读入字符串再解析,或者使用strtok再解析成值,或者使用sscanf,或者使用正则表达式,或者别的什么...
  • 谢谢大家,编译好了。没用,不过这都是我的事。

标签: c++ stream


【解决方案1】:

您可能想试试std::getline 函数:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多