【发布时间】:2016-09-08 23:38:14
【问题描述】:
我正在尝试找到一种方法来拆分字符串以查找数字和特定单词。在这里,我试图读取苹果和橙子的数量。但是,按照我写这个的方式,如果“apple”或“orange”这个词在标点符号之前或之后,它不会被计算在内。例如,考虑文本文件:
3 个苹果 2 个橙子
3个苹果。 2 个橙子。
(3个苹果2个橙子)
这个程序只会计算第一行,因为没有任何标点符号。我希望有人可以向我展示解决此问题的更好方法。
#include <iostream>
#include <string>
#include <fstream>
#include<sstream>
using namespace std;
void readString(string line, int& a, int& o);
//splits the string up into substrings
void assignValue(string str, int& a, int& o, int v);
// takes the word following the value and decides whether to assign it to apples, oranges, or neither
int main()
{
ifstream inStream;
inStream.open(name_of_file);
int apples = 0, oranges = 0;
string line;
while (!(inStream.eof()))
{
getline(inStream, line);
readString(line, apples, oranges);
}
cout << "Apples:" << apples << endl;
cout << "Oranges" << oranges << endl;
inStream.close();
system("pause");
return 0;
}
void readString(string l, int& a, int& o)
{
stringstream ss(l);
string word;
int value = 0;
while (ss >> word)
{
istringstream convert(word
if (convert >> value)
{
ss >> word;
assignValue(word, a, o, value);
}
}
}
void assignValue(string str, int& a, int& o, int v)
{
if (str == "apples")
{
a += v;
}
if (str == "oranges")
{
o += v;
}
}
【问题讨论】:
-
顺便说一句。而不是
while (!(inStream.eof())),您应该只使用if(inStream >> line),因为eof不检查错误,只检查文件结尾。见here。
标签: c++ string parsing char int