【问题标题】:C++ How can I ignore symbols/numbers in a text file when reading it into a string?C ++如何在将文本文件读入字符串时忽略符号/数字?
【发布时间】:2018-04-04 17:49:45
【问题描述】:

我正在做一个项目,我需要制作一个单词计数器来计算文本文件中的唯一单词。在课堂上,我们刚刚学习了 STL,我们应该使用地图制作程序。我从文件中读取的单词并准确计算它们,除了它不会忽略符号或数字,这是我需要它做的。例如,就像现在一样,它计算单词“file”和“file”。作为两个单独的词。我该如何解决?我遇到的另一个问题是单词应该按字母顺序打印。这是我目前所拥有的。

#include <iostream>
#include <map>
#include <fstream>
#include <string>
using namespace std;

template <class words, class counter>
void PrintMap(map<words, counter> map)
{
    typedef std::map<words, counter>::iterator iterator;
    for (iterator p = map.begin(); p != map.end(); p++)
    cout << p->first << ": " << p->second << endl;
}

int main()
{
    static const char* fileName = "D:\\MyFile.txt";

    map<string, int> wordCount;
    {
        ifstream fileStream(fileName);

        if (fileStream.is_open())
            while (fileStream.good())
            {
                string word;
                fileStream >> word;

                if (wordCount.find(word) == wordCount.end())
                    wordCount[word] = 1;
                else
                    wordCount[word]++;
            }
        else 
        {
            cerr << "Couldn't open the file." << endl;
            return EXIT_FAILURE;
        }
        PrintMap(wordCount);
    }
    system("PAUSE");
    return 0;
}

【问题讨论】:

    标签: c++ string dictionary count words


    【解决方案1】:

    您可以编写一个单独的函数来删除每个字符串中不需要的符号,然后再在 wordCount 字典中检查它。例如,在你读完一个新单词后,你可以运行一个小修剪函数,逐个字符地遍历单词,看看是否有任何字符 == a '.'或'-'等。

    【讨论】:

      【解决方案2】:

      原则上,Jake Killpack 的回答是正确的。您可以读取字符串然后对其进行修剪您可以调整在 C++ 中如何读取字符串的行为。根据documentation

      [operator &gt;&gt;] [...] 然后从 is 读取字符并将它们附加到 str 就好像 str.append(1, c),直到满足以下条件之一:

      • [...]
      • std::isspace(c,is.getloc()) 对于 is 中的下一个字符 c 为真(此空白字符保留在输入流中)。

      显然,标点符号不是空格,因此它们也会被阅读并添加到单词中。要改变这一点,您必须调整 std::isspace s.t. 的行为。它将标点符号视为空格,这是可以做到的,即使它很尴尬:

      struct punctws_ctype : std::ctype<char> {
          static const mask* table() {
              static std::vector<mask> v(classic_table(), classic_table() + table_size);
              v[','] |= space; // classify comma as whitespace
              v['.'] |= space; // accordingly...
              v['-'] |= space;
              return &v[0];
          }
      
          my_ctype(std::size_t refs = 0) : std::ctype<char>{ table(), false, refs } { } 
      };
      

      然后,在您在直播中阅读之前:

      // apply the modified behaviour to the stream:
      fileStream.imbue(std::locale{ fileStream.getloc(), new my_ctype });
      

      现在,当使用fileStream &gt;&gt; word 阅读时,它会立即去除所有标点符号。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-18
        • 2017-09-12
        相关资源
        最近更新 更多