save all text from file as string

This is a discussion on save all text from file as string within the C++ Programming forums, part of the General Programming Boards category; This is what I was using to display the first word in a file 'test.txt' Code: char str[10]; ifstream file ...

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    26

    save all text from file as string

    This is what I was using to display the first word in a file 'test.txt'

    Code:
    char str[10];
    ifstream file ( "C:\\test.txt" );
    file >> str;
    cout << str;
    My question is: Is it possible and how to save all the content as a string or to display all of the content and not just one word.

    Thanks.

  2. #2
    Crazy Fool Perspective's Avatar
    Join Date
    Jan 2003
    Location
    Canada
    Posts
    2,640

  3. #3
    Registered User
    Join Date
    Feb 2005
    Posts
    26
    Thanks alot

  4. #4
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,794
    Or, instead of dealing with dynamic memory allocation and needing to seek back and forth in a file just to find its size you can simply do...

    Code:
    #include <iostream>
    #include <sstream>
    #include <string>
    #include <fstream>
    
    using namespace std;
    
    int main()
    {
        ostringstream osstr;
        ifstream input("file.txt");
    
        osstr << input.rdbuf();   // Save entire contents of file into stringstream object
    
        string str(osstr.str());  // Convert stringstream object into string
    
        cout << str << endl;      // Display/use/do something with the string...
    
        return 0;
    }
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading text file into a string obj
    By thetinman in forum C++ Programming
    Replies: 8
    Last Post: 09-02-2008, 11:42 AM
  2. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  3. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 01:19 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 09:46 AM
  5. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 02:23 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21