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

    Storing output in a text file

    Let's suppose I want to append 5 numbers in a file called numbers.txt
    It's running the program; however, it never creates the file numbers.txt; therefore it always displays "file could not be created". Am i missing something?

    Code:
    // ch 9.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include <iostream>
    #include <string>
    #include <fstream>
    
    using namespace std;
    
    int main()
    {
    	int numbers[5] = {0};
    	ofstream numberSequence;
    
    	for (int x = 0; x < 5; x++)
    	{
    		cout << "enter digit " << endl;
    		cin >> numbers[x];
    	
    	}
    
    	cout << endl <<  "These number will be stores in a file:"  <<endl;
    	numberSequence.open("numbers", ios ::app);
    
    	if (!numberSequence.is_open())
    	{
    		for (int p = 0; p < 5; p ++)
    		{
    			cout << endl << numbers[p] << endl;
    			numberSequence << numbers[p] << '#' << endl;
    		}
    	}
    
    	else
    		cout << "file could not be created" << endl;
    
    	system("pause");
    	return 0;
    
    }

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Storing output in a text file

    Your if condition is wrong. Read carefully what it's saying.

  3. #3
    Join Date
    Sep 2011
    Posts
    8

    Re: Storing output in a text file

    Quote Originally Posted by Lindley View Post
    Your if condition is wrong. Read carefully what it's saying.
    if (numberSequence.is_open() == true)

    =-)

    thank you!

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

    Re: Storing output in a text file

    Quote Originally Posted by Pokarface View Post
    if (numberSequence.is_open() == true)

    =-)

    thank you!
    Never compare the boolean values with true. Nor with false.
    Code:
    if( numberSequence.is_open() )
    {
          //  file was opened!
    }
    ...
    if( !numberSequence.is_open() )
    {
          //  file open faled!
    }
    Victor Nijegorodov

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