Help with file Streams

This is a discussion on Help with file Streams within the C++ Programming forums, part of the General Programming Boards category; I need to make this program write to a file and read it. I have got the writing part down ...

  1. #1
    Registered User
    Join Date
    Nov 2001

    Help with file Streams

    I need to make this program write to a file and read it. I have got the writing part down but when it tries to read and display the information i get wierd numbers can anyone tell me whats wrong?

    #include <iostream.h>
    #include <fstream.h>
    #include <iomanip.h>
    #include <stdlib.h>

    int main()

    int num;
    int counter=0;
    int enter;

    ofstream outstream("digits2.dat");

    cout<<"File Problem"<<endl;

    for(counter=0; counter<5; counter++)




    ifstream instream("digits2.dat"); //opens files for reading

    if ( )
    cout<<"File problem!"<<endl;
    exit(1); //stop execution

    while (instream>>num)

    for(counter=0; counter<5; counter++)

    cout<<num<<" ";


    cout<<"There were "<<counter<<" numbers read"<<endl;


    cout<<"\n\n Program finished";

    I am a C++ newb
    using: Visual C++ 6.0
    thanx for any Help

  2. #2
    ell to find a string within a line read from a file, do something like this...
    #include <stdio.h>
    #include <string.h>

    int main ( ) {
    char buff[BUFSIZ];
    FILE *fp = fopen("keywords.txt","r");
    while ( fgets( buff, BUFSIZ, fp ) != NULL ) {
    if ( strstr(buff,"word") != NULL ) {
    printf( "%s", buff );
    fclose( fp );
    return 0;

  3. #3
    have you opened digits2.dat to see what's in it? Maybe you have a problem writing to the file, not reading from it.

    You may need to make a call to clear() after the call to fail(). I generally use the syntax: if(!outstream)

    After the first half of your program you close the ofstream. But then you use it again in the second half of the program without reopening it.

    outstream << 2; might not put anything in the file. to print 2 to the file try this outstream << "2"; or outstream << '2';

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Basic text file encoder
    By Abda92 in forum C Programming
    Replies: 15
    Last Post: 05-22-2007, 02:19 PM
  2. Simple File encryption
    By caroundw5h in forum C Programming
    Replies: 2
    Last Post: 10-13-2004, 11:51 PM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 10:54 AM
  4. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM

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