【问题标题】:C++ int and string parsing with delimiters带分隔符的 C++ int 和字符串解析
【发布时间】: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 &gt;&gt; line),因为eof 不检查错误,只检查文件结尾。见here

标签: c++ string parsing char int


【解决方案1】:

在我看来,这里需要的只是在执行现有的解析代码之前将字符串中的任何标点符号替换为空格,这将很好地将字符串分割成空格分隔的单词。

让我们将“标点”定义为“除字母或数字之外的任何东西”。

您可以在readString() 构造它的std::stringstream 之前使用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 apples”之类的内容作为输入,这当然需要额外的工作,因为这段代码很乐意用空格替换句点。但是,这只是一个心理提示,请牢记。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多