C ++ to read Chinese or English files separated by spaces

// show file content - sbumpc() example
#include <iostream>     // std::cout, std::streambuf
#include <fstream>      // std::ifstream
#include <cstdio>       // EOF

using namespace std;


bool readWord(std::istream& in, std::string& word) {
    int c;
    std::streambuf& sb = *in.rdbuf();
    word.clear();
    cout << "---------------1";

    while ((c = sb.sbumpc()) != EOF) {
        if (c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == '\v' ||
            c == '\f' || c == '\0') {
            
            if (word.empty()) {
                if (c == '\n') {
                    cout << "---------------2";
                    word += "END";
                    return true;
                }
                continue;
            } else {
                if (c == '\n')
                    sb.sungetc(); // advance to next position
                    cout << "---------------5";
                return true;
            }

        }
        cout << "---------------3";
        word.push_back(c);
    }
    // trigger eofbit
    in.get();
    cout << "---------------4" << word.empty();
    return !word.empty();
}

int main () {
  
  std::ifstream fin ("test.txt");
  std::string word;
  while (readWord(fin, word)) {
    cout << word << endl;
  }
  
  
  return 0;
}

test.txt

asdf Hello Great Wall of China 
asAA ASA AS ASA 
vdvsd 
sjklmn 
sdfsdf

Output:

 

Guess you like

Origin www.cnblogs.com/pengwang52/p/11304536.html