Basic C++ File Input/Output Example

  • Sonar Systems admin
    Likes 0

    Problem Description

    Saving and loading from a file.

    Solution Description
    // basic file operations
    #include <iostream>
    #include <fstream>
    
    #include <string>
    
    using namespace std;
    
    int main()
    {
    	string str, str2;
    
    	ifstream writeToFile;
    	writeToFile.open("HelloWorld.txt");
    
    	if ( writeToFile.fail( ) )
    	{
    		cout << "Error opening file" << endl;
    	}
    
    	writeToFile >> str >> str2;
    
    	cout << str.c_str( ) << endl;
    	cout << str2.c_str( ) << endl;
    
    	writeToFile.close( );
    
    	system( "pause" );
    
    	/*
    	ofstream myfile;
    
    	myfile.open( "HelloWorld.txt" );
    
    	myfile << "Hello World.\n";
    	myfile.close( );
    
    	system( "pause" );
    
    	*/
    
    	return EXIT_SUCCESS;
    }

     

Login to reply