【问题标题】:Read text file char by char instead of word by word?逐字符而不是逐字读取文本文件?
【发布时间】:2013-11-30 18:48:58
【问题描述】:

我尝试编写一个从名为 aisha 的文本文件中读取的代码

This is a new file I did it for as a trial for university
but it worked =)
Its about Removing stopwords from the file
and apply casefolding to it
It tried doing that many times
and finally now I could do now

然后代码将读取的文本存储在一个数组中,然后从中删除停用词 但现在我需要做折叠步骤 这段代码逐字读取文本文件的问题

我想逐个字符地读取它,这样我就可以将大小写折叠应用于每个字符 有没有办法让代码按字符读取aisha文件char?

#include <iostream>
#include <string>
#include <fstream>

int main()
{
    using namespace std;

    ifstream file("aisha.txt");
    if(file.is_open())
    {
        string myArray[200];

        for(int i = 0; i < 200; ++i)
        {
            file >> myArray[i];

            if (myArray[i] !="is" && myArray[i]!="the" && myArray[i]!="that"&& myArray[i]!="it"&& myArray[i]!="to"){
            cout<< myArray[i]<<"  ";
            }


        }
    }
system("PAUSE");
return 0;
}

【问题讨论】:

  • 你的数组应该是一个字符数组而不是字符串。
  • 好的,但是停用词的部分不起作用也许我会制作另一个数组
  • @AishaAhmedAhmed 你对使用向量好吗?如果您对此感到满意,我有一个使用向量的答案。
  • Cygwinnian 不,我还是个初学者

标签: c++ text


【解决方案1】:

如果您将数组声明为 char 数组而不是字符串数组,则提取运算符将自动读取 char。

您还必须小心,因为 >> 运算符默认会跳过空白字符。如果您还想读取空格,则应在读取字符之前添加 noskipws。

file >> std::noskipws;

【讨论】:

  • 我有一个小问题 >> 我应该在哪里添加文件 >> std::noskipws;在代码中?
【解决方案2】:

此链接解释了执行此操作的 C++ 方法:http://www.cplusplus.com/reference/istream/istream/get/

#include <iostream>     // std::cin, std::cout
#include <vector>       // store the characters in the dynamic vector
#include <fstream>      // std::ifstream

int main () {

  std::ifstream is("aisha.txt");     // open file and create stream
  std::vector <char> stuff;

  while (is.good())          // loop while extraction from file is possible
  {
    char c = is.get();       // get character from file
    if (is.good())
      std::cout << c;        // print the character
      stuff.push_back(c);    // store the character in the vector
  }

  is.close();                // close file

  return 0;
}

现在您基本上将文件的每个字符都存储在称为stuff 的向量中。您现在可以对这个向量进行修改,因为它是数据的更简单的内部表示。此外,您还可以访问所有方便的 STL 方法。

【讨论】:

    【解决方案3】:

    使用整个字符串而不是逐个字符地读取字符 使用 readline 函数。

    【讨论】:

      猜你喜欢
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-12
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多