Results 1 to 4 of 4

Thread: Text save problem

  1. #1

    Thread Starter
    Member
    Join Date
    Aug 2001
    Posts
    33

    Text save problem

    Hi.

    I'm a newbie on C++ and I have a problem with my program.

    My program randoms a bunch of names and the puts the out on the screen and I want to save the text in a file (the same text as the screen shows).

    Here's the basic code:

    Code:
    char c[4][6] = {"Tony,"James","Johnny","Lars"};
    
    srand((unsigned)time(NULL));
    
    
    for (i=0;i<4;i++){
    
        cout<<c[rand() % 4]<<"\n";
    
    }
     // save code?
    Now I want to save the random names that are put out on the screen.

    Please help.

  2. #2
    Lively Member
    Join Date
    Dec 2000
    Location
    Indiana
    Posts
    73
    Code:
    //****REQUIRES FSTREAM.H****\\
    
    char c[4][6] = {"Tony,"James","Johnny","Lars"};
    
    ofstream a_file("output.txt");
    srand((unsigned)time(NULL));
    
    for (i=0;i<4;i++){
    
        cout<<c[rand() % 4]<<"\n";
        a_file<<c[rand() % 4]<<"\n";
    
    }
    a_file.close();
    Thanks to
    www.cprogramming.com

  3. #3

    Thread Starter
    Member
    Join Date
    Aug 2001
    Posts
    33
    Thanks but that doesn't work, I tried it before. The text that is printed out on the screen and the text that is being put in the textfile is different. Maybe I need to store the randomized names in a array or something?
    Any other ideas?

  4. #4
    jim mcnamara
    Guest
    ansi i/o works

    [code]
    #include <stdio.h>
    int j;

    FILE *fptr;
    char c[4][6] = {"Tony,"James","Johnny","Lars"};

    srand((unsigned)time(NULL));

    fptr = fopen("myfile.txt");

    for (i=0;i<4;i++){
    j = rand() % 4;
    // comment out since you're writing to a file --
    // cout << c[j] << '\n';
    fprintf( "%s\n", c[j] );
    }

    flcose(fptr);

    [/close]
    PS: this does work;
    don't bunch up everything - the compiler doesn't care but you will later on. Readability counts.

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