简体   繁体   中英

Read text file char by char instead of word by word?

I tried to make a code that reads from text file called 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

and then the code stores the read text on an array and then removes the stopwords from it but now I nead to make the case folding step the problem that this code reads the text file word by word

I want to read it char by char so I can apply casefolding to each char is there ant way to make the code read the aisha file char by 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;
}

If you declare your array as an array of char instead of array of strings, the extraction operator shall automatically read char.

Also you will have to be careful because the >> operator by default skips the whitespace characters. If you want to read the whitespaces also, then you should add noskipws before reading the characters.

file >> std::noskipws;

The C++ way to do this is explained at this link: 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;
}

Now you basically have every character of the file stored in the vector known as stuff . You can now do your modification to this vector, for it is a far easier internal representation of data. Also, you have access to all the handy STL methods.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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