CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Apr 2013
    Posts
    77

    get data from input stream c++

    Code:
    #include <fstream>
    #include <string>
    using namespace std;
    
    ifstream inf("file name");
    string line;
    
        while (inf.good()) {
            getline(inf, line);
               }
    instead of line by line i want the complete data from file to the string.What modification i have to do?

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: get data from input stream c++

    Victor Nijegorodov

  3. #3
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: get data from input stream c++

    There are a few ways, e.g., you could read line by line and then append to a string. However, one way that comes to mind is:
    Code:
    #include <fstream>
    #include <sstream>
    #include <string>
    
    int main()
    {
        using namespace std;
        ifstream inf("file name");
        stringstream ss;
        ss << inf.rdbuf();
        string content = ss.str();
        // ...
    }
    By the way, your method of reading line by line is wrong. You should not be calling inf.good() to control the loop. Rather:
    Code:
    while (getline(inf, line)) {
        // ...
    }
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  4. #4
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: get data from input stream c++

    Here's another way
    Code:
    #include <fstream>
    #include <string>
    
    int main()
    {
        std::string str;
        std::ifstream inf("file name");
        inf.seekg(0, std::ios::end);
        str.resize(inf.tellg());
        inf.seekg(0, std::ios::beg);
        inf.read(&str[0], str.size());
    }
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured