繁体   English   中英

按字符读取文本文件,而不是逐字读取吗?

[英]Read text file char by char instead of word by word?

我试图制作一个从文本文件中读取的代码,称为艾莎

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

然后代码将读取的文本存储在数组上,然后从数组中删除停用词,但是现在我需要使案例折叠步骤成为此代码逐字读取文本文件的问题

我想按字符读取char,因此我可以对每个字符应用大小写折叠,是否有蚂蚁方法使代码按char读取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;
}

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

另外,您还必须小心,因为>>运算符默认情况下会跳过空格字符。 如果还要阅读空格,则应在阅读字符之前添加noskipws。

file >> std::noskipws;

此链接说明了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方法。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM