read word by word from file in C++

后端 未结 5 895
清歌不尽
清歌不尽 2020-12-01 12:53

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          


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 13:11

    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):

    while ( ! file.eof() )
    {
        std::ifstream::int_type x = file.get();
    
        while ( x != ' ' && x != std::ifstream::traits_type::eof() )
        {
            word += static_cast(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 
    #include 
    
    void readFile(  )
    {
        std::ifstream file("program.txt");
        std::copy(std::istream_iterator(file), 
                  std::istream_itetator(), 
                  std::ostream_iterator(std::cout, "\n"));
    }
    

提交回复
热议问题