[英]C++ int and string parsing with delimiters
我试图找到一种方法来分割字符串来查找数字和特定的单词。 在这里,我试图读取苹果和橘子的数量。 但是,我写这个的方式,如果单词“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;
}
}
在我看来,这里所需要的就是在执行现有的解析代码之前将字符串中的任何标点符号替换为空格,这样就可以很好地将字符串切换成以空格分隔的单词。
我们将“标点符号”定义为“除字母或数字之外的任何内容”。
您可以在构造其std::stringstream
之前在readString()
使用std::replace_if
():
std::replace_if(l.begin(), l.end(), [](char c) { return !isalnum(c) }, ' ');
或者,如果你想有点明确:
for (char &c:l)
{
if (!isalnum(c))
c=' ';
}
现在,所有标点符号现在都被空格替换,现有的代码在此之后应该很好地清理。
如果您的数值可能是小数,则可能出现的复杂情况。 由于您将它们声明为int
,因此情况并非如此。 但是,如果你必须接受类似“4.5苹果”之类的东西作为输入,那么这将需要额外的工作,因为这段代码将很乐意用空格替换句号。 但是,这只是一个心理记录,要记住。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.