【发布时间】:2015-04-14 23:28:03
【问题描述】:
我正在尝试从文本文件中输入数据: 行格式如下... 字符串|字符串|int double
示例: 鲍勃|橙子|10 .89
我可以使用 Getline(infile, line)
我不明白如何将行拆分为字符串变量中的不同变量。
谢谢
【问题讨论】:
我正在尝试从文本文件中输入数据: 行格式如下... 字符串|字符串|int double
示例: 鲍勃|橙子|10 .89
我可以使用 Getline(infile, line)
我不明白如何将行拆分为字符串变量中的不同变量。
谢谢
【问题讨论】:
首先,您可以使用 strchr 编写一些不错的老式 c 代码。
如果您使用的是 std::String,则使用 string.find / find_first_of
http://www.cplusplus.com/reference/string/string/find_first_of/
【讨论】:
您将此标记为 C++。所以也许你应该尝试使用格式化的提取器......
这是一个“ram”文件(就像磁盘文件一样工作)
std::stringstream ss("Bob|oranges|10 .89");
// this ^^^^^^^^^^^^^^^^^^ puts one line in file
我会对两个字符串使用 getline,并带有小节终止符
do {
std::string cust;
(void)std::getline(ss, cust, '|'); // read to 1st bar
std::string fruit;
(void)std::getline(ss, fruit, '|'); // read to 2nd bar
然后直接读取int和float:
int count = 0;
float cost;
ss >> count >> cost; // the space char is ignored by formatted extraction
std::cout << "\ncust: " << cust << "\n"
<< " " << count << " " << fruit
<< " at $" << cost
<< " Totals: " << (float(count) * cost) << std::endl;
if(ss.eof()) break;
}while(0);
如果要处理更多的行,则需要找到eoln,并为上述样式的每条记录重复。
这种方法非常脆弱(格式的任何更改都会强制更改您的代码)。
这只是为了让您开始。根据我的经验,使用 std::string find 和 rfind 的脆弱性要小得多。
祝你好运。
【讨论】: