Thread: Help using C++ stream classes

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    46

    Help using C++ stream classes

    Hello, I am new to this forum and happy to be a new member and eager to learn from you guys! I have this code dealing with C++ stream classes and I can't seem to get it to work. It seems simple enough, I need to read contents of a file and list them in the output. Could someone please advise how I can get this to compile and run correctly on VC++.net? I have also tried this on Dev-C++ compiler and it will not work for me. I know something with the source code is wrong. Could it be that I am using "old" style and trying to use fstream.h ?

    Code:
    #include <iostream>
    #include <fstream.h>
    
    using namespace std;
    
    void main ()
    {
    	char ch;
    	fstream file;
    
    	char filename[20];
    	cout << "Enter the name of the file: " 
    		<<flush;
    	cin >> filename;
    	file.open(filename, ios::in);
    	file.unsetf(ios::skipws);
    	
    
    	while (1)
    	{
    		file >> ch;
    		if (file.fail()) break;
    		cout << ch;
    	}
    	file.close();
    }
    Thanks in advance!!

  2. #2
    erstwhile
    Join Date
    Jan 2002
    Posts
    2,227
    Hello, welcome to the boards.
    Code:
    #include <iostream>
    #include <fstream> //<-- no file extension
    
    using namespace std;
    
    int main ()
    {
    	char ch;
    	fstream file;
    
    	char filename[20];
    	cout << "Enter the name of the file: " 
    		<<flush;
    	cin >> filename;
    	file.open(filename, ios::in);
    	file.unsetf(ios::skipws);
    	
    
    	while (1)
    	{
    		file >> ch;
    		if (file.fail()) break;
    		cout << ch;
    	}
    	file.close();
    }
    No void main
    CProgramming FAQ
    Caution: this person may be a carrier of the misinformation virus.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >#include <fstream.h>
    While this may work on older compilers, the current C++ standard makes no mention of this header. Use <fstream> instead.

    >void main ()
    main does not, and never has, returned void. The following is the correct definition of main taking no arguments:
    Code:
    int main()
    {
      // Stuff
    }
    Here is one way to do it properly:
    Code:
    #include <cstdlib>
    #include <fstream>
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
      // 1
      string filename;
    
      // 2
      cout<<"Enter a file to open: ";
    
      // 3
      if ( !getline ( cin, filename ) ) {
        cerr<<"Input error"<<endl;
        return EXIT_FAILURE;
      }
    
      // 4
      ifstream in ( filename.c_str() );
    
      // 5
      if ( !in ) {
        cerr<<"Error opening file"<<endl;
        return EXIT_FAILURE;
      }
    
      // 6
      char ch;
    
      // 7
      while ( in.get ( ch ) )
        cout.put ( ch );
    
      // 8
      cout<<endl;
    
      // 9
      return EXIT_SUCCESS;
    }
    I've commented the areas that I'll...um...comment on.

    1) The C++ string class is much better than C-style strings. You don't need to set a size for them because they grow to meet your needs, you don't have to worry about a trailing null character, and they have a slew of useful methods. I highly recommend you start out using C++ strings and then move on to C-style strings because they're actually harder.

    2) Notice that there's no need to flush the stream if an input operation follows. This is a convenience born from experience with C.

    3) getline is much better than cin's >> operator for reading string input. Not only do you avoid the issue where >> stops at whitespace, you also avoid the subtle bug of leaving junk in the stream for other input operations to break on.

    4) Unless you have a very good reason, it's best to initialize objects when you define them. This is easily done with constructors.

    5) Always, I'll say again, ALWAYS, check to see if your file is opened and ready to go. This is especially important here because the user (a notoriously inaccurate data entry mechanism) is supplying a file name.

    6) It's good to declare your variables just before you need them. That way readers don't have to search all over the place to find where an uninformatively named variable (such as ch) is used.

    7) cin and cout both have overloaded functions that handle single characters. What's even better is that the return value from get can be used as a condition for a loop. If it returns a true value then data was read and you can keep going. If it returns a false value then either there was a catastrophic error, or you reached the end of input...generally we suggest that you determine which of these is the case in real programs. But for now you can ignore it and assume end-of-file.

    8) It's always a good idea to clean up the output stream for future programs. In this case I assume that the console window is shared and that printing another newline will allow the next program to start at column 0. Be a good neighbor.

    9) EXIT_SUCCESS is equivalent to 0 and defined in <cstdlib> along with EXIT_FAILURE. Notice that I neglected to close the file as well. This is because the destructor does that for me. Unless you plan on using the object for opening another file or you don't plan on leaving the object's scope for a while, you can let the destructor handle closing and such.
    My best code is written with the delete key.

  4. #4
    Registered User
    Join Date
    Sep 2004
    Posts
    46
    Thanks for your responses so quickly! I am going to love this place, already learning!

    First thing I tried was getting rid of the "void main" and I used int main and I got rid of the ".h" file extension. This allowed the program to run and prompted me to enter the name of the file I wish to read, however, when I type in the name of the file it simply prompts me to press any key to continue and exits the program, it doesnt read anything...?? Am I possibly doing something wrong with the file name?

    Second, I copied Prelude's code and tried running that and it gave me a problem with the file as well "error opening file" which means that it wasn't "in". What could I be doing wrong?

    I created this file in notepad and am typing in the name of the file for the program to read, but I am obviosly doing something really silly! What could it be?

    Also thanks to Ken and Prelude for the responses!

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Am I possibly doing something wrong with the file name?
    >gave me a problem with the file as well "error opening file"
    I imagine the first would be undefined behavior because the file wasn't found and your code didn't check for that. The second was my carefully crafted error message notifying you that the file you typed wasn't where the program looked for it. Try giving the full path of the file, or if you're running this program from the IDE, find out where your compiler looks for files (such as the same location as the project file or the executable) and place it there.
    My best code is written with the delete key.

  6. #6
    Registered User
    Join Date
    Sep 2004
    Posts
    46
    Quote Originally Posted by Prelude
    >Am I possibly doing something wrong with the file name?
    >gave me a problem with the file as well "error opening file"
    I imagine the first would be undefined behavior because the file wasn't found and your code didn't check for that. The second was my carefully crafted error message notifying you that the file you typed wasn't where the program looked for it. Try giving the full path of the file, or if you're running this program from the IDE, find out where your compiler looks for files (such as the same location as the project file or the executable) and place it there.
    Well the error is def. the one notifying me the typed file was'nt where the program looked for it, so I then, typed the full path and it still gave me the same error????

    I am using notepad to create the text file, and using VC++.net to write source and compile

  7. #7
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >I am using notepad to create the text file, and using VC++.net to write source and compile
    Where are you running the program from and where is the file located? I've found that an easy way to test a file driven program with Visual C++ .NET is to run the program with Ctrl+F5 and to place the file in the same directory as the project file (C:\Documents and Settings\JWalker\My Documents\Visual Studio Projects\Cpp. Change the names accordingly if you use the default directories like I do). Then all you have to do is type the name of the file when prompted by the program, for example:
    Code:
    Enter a file to open: input.txt
    No muss, no fuss, and everything has a tendency to work. Especially if you make a habit of doing it the same way every time.
    My best code is written with the delete key.

  8. #8
    Registered User
    Join Date
    Sep 2004
    Posts
    46
    Quote Originally Posted by Prelude
    >I am using notepad to create the text file, and using VC++.net to write source and compile
    Where are you running the program from and where is the file located? I've found that an easy way to test a file driven program with Visual C++ .NET is to run the program with Ctrl+F5 and to place the file in the same directory as the project file (C:\Documents and Settings\JWalker\My Documents\Visual Studio Projects\Cpp. Change the names accordingly if you use the default directories like I do). Then all you have to do is type the name of the file when prompted by the program, for example:
    Code:
    Enter a file to open: input.txt
    No muss, no fuss, and everything has a tendency to work. Especially if you make a habit of doing it the same way every time.
    Well, I tried saving to the exact path using the Ctrl + F5 and the program is still not reading the file for some reason, with both examples of the program. The first version still just prompts for the name of file, and then exits..........The second (Prelude's) just gives the error opening file....this problem seems like its just something small I just can't put a finger on it, thanks in advance for any help!!!!

  9. #9
    Registered User
    Join Date
    Sep 2004
    Posts
    46
    Well I am still having trouble just getting this program to read the input file, any other suggestions would be really appreciated!

  10. #10
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    If all else fails, take the executable of your program and the text file and place them both in the root directory. Then open up the command prompt and do this:
    Code:
    C:\prog input.txt
    Changing names to match your files of course.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can you Initialize all classes once with New?
    By peacerosetx in forum C++ Programming
    Replies: 12
    Last Post: 07-02-2008, 10:47 AM
  2. Help! About text stream and binary stream
    By Antigloss in forum C Programming
    Replies: 1
    Last Post: 09-01-2005, 08:40 AM
  3. Multiple Inheritance - Size of Classes?
    By Zeusbwr in forum C++ Programming
    Replies: 10
    Last Post: 11-26-2004, 09:04 AM
  4. im extreamly new help
    By rigo305 in forum C++ Programming
    Replies: 27
    Last Post: 04-23-2004, 11:22 PM
  5. Exporting VC++ classes for use with VB
    By Helix in forum Windows Programming
    Replies: 2
    Last Post: 12-29-2003, 05:38 PM