C++读取中文或英文文件空格分割

// 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 你好 中国 万里 长城
asaa asa as asa
vdvsd
sjklmn
sdfsdf

输出:

 

posted on 2019-08-05 17:53  TMatrix52  阅读(547)  评论(0编辑  收藏  举报

导航