Ich versuche eine Möglichkeit zu finden, eine Zeichenfolge zu teilen, um Zahlen und bestimmte Wörter zu finden. Hier versuche ich die Anzahl der Äpfel und Orangen zu lesen. So wie ich das geschrieben habe, wenn das Wort "Apfel" oder "Orange" vor oder nach Satzzeichen steht, zählt es nicht. Betrachten Sie zum Beispiel die Textdatei:C++ int und String-Parsing mit Trennzeichen
3 Äpfel 2 Orangen
3 Äpfel. 2 Orangen.
(3 Äpfel 2 Orangen)
Dieses Programm wird nur die erste Zeile abrechnen, da es keine Interpunktion gibt. Ich hatte gehofft, jemand könnte mir eine bessere Herangehensweise an dieses Problem zeigen.
#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;
}
}
als beiseite. Anstelle von while (! (InStream.eof())) 'sollten Sie einfach' if (inStream >> line) 'verwenden, da' eof' nicht auf Fehler prüft, sondern nur auf das Ende der Datei. Siehe [hier] (http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-sidered-wrong). –