C++ 用C++从文件中逐字读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20372661/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:05:34  来源:igfitidea点击:

read word by word from file in C++

c++

提问by M.Tamimi

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??

任何人都知道问题是什么以及如何解决?

回答by Some programmer dude

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

首先,不要循环while (!eof()),它不会像您期望的那样工作,因为eofbit直到由于文件结束导致读取失败才会设置循环。

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

其次,普通输入操作符>>在空格上分开,因此可用于读取“单词”:

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

回答by Deidrei

I have edited the function for you,

我已经为你编辑了这个函数,

void readFile()
{
    ifstream file;
    file.open ("program.txt");
    if (!file.is_open()) return;

    string word;
    while (file >> word)
    {
        cout<< word << '\n';
    }
}

回答by Pandrei

what you are doing here is reading one character at a time from the input stream and assume that all the characters between " " represent a word. BUT it's unlikely to be a " " after the last word, so that's probably why it does not work:

您在这里所做的是一次从输入流中读取一个字符,并假设“”之间的所有字符都代表一个单词。但是在最后一个单词之后不太可能是“”,所以这可能是它不起作用的原因:

"word1 word2 word2EOF"

回答by Phi

If I may I could give you some new code for the same task, in my code you can create a so called 'document'(not really)and it is saved, and can be opened up again. It is also stored as a string file though(not a document). Here is the code:

如果可以的话,我可以给你一些相同任务的新代码,在我的代码中,你可以创建一个所谓的“文档”(不是真的),它被保存,可以再次打开。它也存储为字符串文件(不是文档)。这是代码:

#include "iostream"

#include "windows.h"

#include "string"

#include "fstream"

using namespace std;

int main() {

string saveload;


cout << "---------------------------" << endl;
cout << "|enter 'text' to write your document    |" << endl;
cout << "|enter 'open file' to open the document |" << endl;
cout << "----------------------------------------" << endl;
while (true){
    getline(cin, saveload);

    if (saveload == "open file"){
        string filenamet;
        cout << "file name? " << endl;
        getline(cin, filenamet, '*');
        ifstream loadFile;

        loadFile.open(filenamet, ifstream::in);

        cout << "the text you entered was: ";

        while (loadFile.good()){

            cout << (char)loadFile.get();

            Sleep(100);
        }

        cout << "" << endl;

        loadFile.close();

    }

    if (saveload == "text") {
        string filename;
        cout << "file name: " << endl;
        getline(cin, filename,'*');
        string textToSave;
        cout << "Enter your text: " << endl;
        getline(cin, textToSave,'*');

        ofstream saveFile(filename);

        saveFile << textToSave;

        saveFile.close();

    }
}
return 0;
}

Just take this code and change it to serve your purpose. DREAM BIG,THINK BIG, DO BIG

只需使用此代码并对其进行更改即可满足您的目的。梦想大,想大,做大

回答by Christian Rau

As others have said, you are likely reading past the end of the file as you're only checking for x != ' '. Instead you also have to check for EOF in the inner loop (but in this case don't use a char, but a sufficiently large type):

正如其他人所说,您可能会读到文件末尾,因为您只检查x != ' '. 相反,您还必须在内循环中检查 EOF(但在这种情况下,不要使用字符,而是使用足够大的类型):

while ( ! file.eof() )
{
    std::ifstream::int_type x = file.get();

    while ( x != ' ' && x != std::ifstream::traits_type::eof() )
    {
        word += static_cast<char>(x);
        x = file.get();
    }
    std::cout << word << '\n';
    word.clear();
}

But then again, you can just employ the stream's streaming operators, which already separate at whitespace (and better account for multiple spaces and other kinds of whitepsace):

但话又说回来,你可以只使用流的流操作符,它们已经在空格处分开(更好地考虑多个空格和其他类型的空格):

void readFile(  )
{
    std::ifstream file("program.txt");
    for(std::string word; file >> word; )
        std::cout << word << '\n';
}

And even further, you can employ a standard algorithm to get rid of the manual loop altogether:

更进一步,您可以使用标准算法来完全摆脱手动循环:

#include <algorithm>
#include <iterator>

void readFile(  )
{
    std::ifstream file("program.txt");
    std::copy(std::istream_iterator<std::string>(file), 
              std::istream_itetator<std::string>(), 
              std::ostream_iterator<std::string>(std::cout, "\n"));
}