数値と特定の単語を検索するために文字列を分割する方法を見つけようとしています。ここで私はリンゴとオレンジの数を読み込もうとしています。しかし、私がこれを書いたやり方では、 "りんご"や "オレンジ"という言葉の前後に句読点があると、それはカウントされません。たとえば、テキストファイルを考えてみましょう。デリミタを使用したC++のintと文字列の解析
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'はエラーをチェックせず、ファイルの終わりだけをチェックします。 [ここ](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong)を参照してください。 –