从C ++中的文件中逐字读取 [英] read word by word from file in C++

查看:202
本文介绍了从C ++中的文件中逐字读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个函数应该通过字
读取一个文件字,直到最后一个字,运行停止。

this function should read a file word by word and it does work till the last word, where the run stops

void readFile(  )
{
    ifstream file;
    file.open ("program.txt");
    string word;
    char x ;
    word.clear();

    while ( ! file.eof() )
    {
        x = file.get();

        while ( x != ' ' )
        {
            word = word + x;
            x = file.get();
        }

            cout<< word <<endl;
            word.clear();

    }
}

任何一个看到什么问题如何解决?

any one see what is the problem and how it can be solved??

推荐答案

首先,不要循环 while eof()),它将无法正常工作,因为 eofbit

First of all, don't loop while (!eof()), it will not work as you expect it to because the eofbit will not be set until after a failed read due to end of file.

其次,正常输入操作符>> 在空格分隔因此可以用于读取字词:

Secondly, the normal input operator >> separates on whitespace and so can be used to read "words":

std::string word;
while (file >> word)
{
    ...
}

这篇关于从C ++中的文件中逐字读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆