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   TMatrix52  阅读(557)  评论(0编辑  收藏  举报

编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示