Like Tree1Likes

I/O files: reading, manipulating and outputting data

This is a discussion on I/O files: reading, manipulating and outputting data within the C++ Programming forums, part of the General Programming Boards category; I wish to input (read) the contents of the file called "numbers.dat" (that appears at the bottom of this writeup) ...

  1. #1
    Registered User
    Join Date
    Dec 2012
    Posts
    9

    I/O files: reading, manipulating and outputting data

    I wish to input (read) the contents of the file called "numbers.dat" (that appears at the bottom of this writeup) into the file (sum.dat) following immediately here below; with the view of manipulating these contents and outputting the results within this file called "sum.dat". However, all my previous attempts have ended with: "Input file opening failed"!

    I am using Code::Blocks 10.05 running on Windows.

    I am unable to figure out why the input file fails to open. What is wrong here?

    Code:
    #include <fstream>
    #include <iostream>
    #include <cstdlib>
    
    int main()
    {
        using namespace std;
    
        char in_file_name[16], out_file_name[16];
        ifstream in_stream;
        ofstream out_stream;
    
        cout << "Enter the input file name (maximum of 15 characters):\n";
        cin >> in_file_name;
        cout << "Enter the output file name (maximum of 15 characters):\n";
        cin >> out_file_name;
        cout << "I will read numbers from the file "
             << in_file_name << " and\n"
             << "place the sum in the file "
             << out_file_name << endl;
    
        in_stream.open(in_file_name);
        if (in_stream.fail ())
        {
            cout << "Input file opening failed.\n";
            exit(1);
    
            out_stream.open(out_file_name);
            if (out_stream.fail ())
            {
                cout << "Output file opening failed.\n";
                exit(1);
            }
            int first, second, third;
            in_stream >> first >> second >> third;
    
            out_stream << "The Sum of the first 3\n"
                       << "numbers in " << in_file_name << endl
                       << " is " << (first + second + third)
                       << endl;
    
            in_stream.close();
            out_stream.close();
    
            cout << " End of Program.\n";
    
        }
    
        return 0;
    }
    //Following is the file numbers.dat

    Code:
    #include <fstream>
    #include <string>
    #include <iostream>
    #include <cstdlib>
    
    using namespace std;
    
    int main()
    {
        int num1, num2, num3, num4;
        string numbers;
    
        cout << "Enter the four numbers: " << endl;
        cin >> num1 >> num2 >> num3 >> num4;
    
        cout << "The numbers are: " << num1 << " "<< num2 << " " 
                                                   << num3      << " " << num4;
    
        ofstream writer("numbers.dat");
    
        if(!writer)
        {
            cout << "Error opening file for output" << endl;
            return -1;
        }
        writer << numbers << endl;
        writer.close();
    
        return 0;
    }

  2. #2
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,403
    I think you have a problem with the basic io concept here?

    why is numbers.dat another program? do think numbers.dat will somehow 'run' when it opens? also if you know you want to open numbers.dat, then why are you asking for input? - also your logic is messed up -Am i missing something here?
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,892
    And please use std::string instead of char arrays for the file names. You can use the c_str() member to get something you can pass to stream's open method.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  4. #4
    Registered User
    Join Date
    Dec 2012
    Posts
    9
    It is possible that I don't have a proper grasp of the IO concept and my logic in dealing with this problem is flawed. As a matter of fact, I am trying to learn C++ on my own (teaching myself!). This is a C++ example I got from Walter Savitch's book (Problem Solving with C++ - 7th Edition).

    I hoped to create a program that would generate a file called numbers.dat. Then this program would ask for 4 numbers that I would input. Accordingly, the 4 numbers would be stored in the file numbers.dat that would be saved on its own.

    Then I would go ahead and, independently, create another program with a file called sum.dat. This new program will use the contents of the old file (numbers.dat). In essence, the new program is meant to open numbers.dat and add some of the inputs therein, before it moves/ stores the total (sum) of the first 3 inputs in numbers.dat to the file called sum.dat.

    Thus, it is envisaged, if you input the numbers: 1,2,3, and 4 in the program that creates the file numbers.dat, then you should have the number (1+2+3) i.e. 6 in the file sum.dat if the second program (that sums the first 3 contents of the file numbers.dat) opens its numbers.dat and performs as required. I assume that the second program should be able to open that file called numbers.dat and access its contents that were input in the first place!

    Thanks for your interest in my problem and your assistance is much appreciated.

  5. #5
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,892
    Your approach isn't bad, but you're confusing the intended output of the first program (a file called numbers.dat) with the program itself (you wrote the source into a file called numbers.dat).
    So what you want to do is put the second snippet above into a .cpp file and compile it. Then you run the resulting program. (But first you have to fix the bug where you put a string called numbers into the output file, which you never give a meaningful value.) This should create the numbers.dat file.
    Then you can run the other program, which should read the numbers.dat file.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  6. #6
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,403
    does the book example you are following actually specify the creation of two programs? Thats fine if it does for the purposes of your exercise, but consider the wider picture - your program could first collect the data for numbers.dat, and then you could go on to also do the other work - in the same program - the user could input request for it. - you must by now have read of functions - is there a difference between that idea and another seperate program? - by the way I, and many other regulars on this board are self taught :->

    A note on the logic - In your first example you ask if the file is ok- if not exit - the flow cannot progress beyond that point to do the other things in the statement as you put an exit call in to stop anything else being looked at even if you meant to in the event of said problem, and in fact if the file was good to start with then nothing else would happen. - Also the exit() call in my own probably limited experience i have very rarely seen used.
    What you want is to check if file is good, then go on to read your input into the file, finish that, close file. - else if file not good, output an error
    Last edited by rogster001; 12-07-2012 at 05:00 PM.
    Lesshardtofind likes this.
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  7. #7
    Registered User
    Join Date
    Dec 2012
    Posts
    9

    I/O files: reading, manipulating and outputting data

    Thanks CornedBee! I have done everything - including commenting out the string called numbers - as you advised. I did save the second snippet under the name numbers.cpp, before I had it compiled and run successfully with the necessary inputs. However, when I attempted to run the other program in the first snippet it could not open the file "numbers.dat". This other program still says that "Input file opening failed".

    Any other ideas on how to overcome this? I appreciate!!

  8. #8
    Registered User rogster001's Avatar
    Join Date
    Aug 2006
    Location
    Liverpool UK
    Posts
    1,403
    so you now have a numbers.dat file successfully created? you can open it on your operating system and its contents are as expected?- what is the path you are supplying to your file reading program? the path for numbers.dat?
    Thought for the day:
    "Are you sure your sanity chip is fully screwed in sir?" (Kryten)
    FLTK: "The most fun you can have with your clothes on."

    Stroustrup:
    "If I had thought of it and had some marketing sense every computer and just about any gadget would have had a little 'C++ Inside' sticker on it'"

  9. #9
    Registered User
    Join Date
    Dec 2012
    Posts
    9
    Thanks rogster001. The file numbers.dat was created. However, it is blank and as such does not contain the numbers that I input.

  10. #10
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,892
    Well, show the updated numbers.cpp program. I suspect you're not actually writing the numbers.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  11. #11
    Registered User
    Join Date
    Dec 2012
    Posts
    9

    I/O files: reading, manipulating and outputting data

    Here below is the updated numbers.cpp program. When I run it, I am prompted to input the required 4 numbers as expected. I did input the 4 numbers. However, after that only a blank numbers.dat is created. Thanks!


    Code:
    #include <fstream>
    #include <string>
    #include <iostream>
    #include <cstdlib>
    using namespace std;
    
    int main()
    {
    int num1, num2, num3, num4;
    //string numbers;
    cout << "Enter the four numbers: " << endl;
    cin >> num1 >> num2 >> num3 >> num4;
    cout << "The numbers are: " << num1 << " "<< num2 << " " << num3 << " " << num4;
    ofstream writer("numbers.dat");
    if(!writer)
    {
    cout << "Error opening file for output" << endl;
    return -1;
    }
    // writer << numbers << endl;
    writer.close();
    return 0;
    }

  12. #12
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,892
    Well, you don't actually write the numbers to the file, as I suspected. You commented out the "numbers" line, but you didn't add anything in its stead. (Hint: it should be similar to the line where you echo the numbers back to the user.)
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  13. #13
    Registered User
    Join Date
    Dec 2012
    Posts
    9

    I/O files: reading, manipulating and outputting data

    Thanks CornedBee! One issue is now resolved. The file numbers.dat now contains the numbers input in the program. However, when I run the other program from the first snippet (that I also reproduce below for clarity/ convenience), it is still unable to open numbers.dat and sum up the numbers contained in the file numbers.dat as required of it. I still get the "input file opening failed" message. I reproduce the corrected numbers.cpp program and the other program - that is meant to open the file numbers.dat and sum up its contents - that appeared in the first snippet.

    Code:
    #include <fstream>
    #include <string>
    #include <iostream>
    #include <cstdlib>
    using namespace std;
    
    int main()
    {
    int num1, num2, num3, num4;
    //string numbers;
    cout << "Enter the four numbers: " << endl;
    cin >> num1 >> num2 >> num3 >> num4;
    cout << "The numbers are: " << num1 << " "<< num2 << " " << num3 << " " << num4;
    ofstream writer("numbers.dat");
    if(!writer)
    {
    cout << "Error opening file for output" << endl;
    return -1;
    }
    writer << num1 << num2 << num3 << num4 << endl;
    writer.close();
    return 0;
    }
    Next is the other program

    Code:
    #include <fstream>
    #include <iostream>
    #include <cstdlib>
    
    int main()
    {
    using namespace std;
    char in_file_name[16], out_file_name[16];
    ifstream in_stream;
    ofstream out_stream;
    cout << "Enter the input file name (maximum of 15 characters):\n";
    cin >> in_file_name;
    cout << "Enter the output file name (maximum of 15 characters):\n";
    cin >> out_file_name;
    cout << "I will read numbers from the file "
    << in_file_name << " and\n"
    << "place the sum in the file "
    << out_file_name << endl;
    in_stream.open(in_file_name);
    if (in_stream.fail ())
    {
    cout << "Input file opening failed.\n";
    exit(1);
    out_stream.open(out_file_name);
    if (out_stream.fail ())
    {
    cout << "Output file opening failed.\n";
    exit(1);
    }
    int first, second, third;
    in_stream >> first >> second >> third;
    out_stream << "The Sum of the first 3\n"
    << "numbers in " << in_file_name << endl
    << " is " << (first + second + third)
    << endl;
    in_stream.close();
    out_stream.close();
    cout << " End of Program.\n";
    }
    return 0;
    }

  14. #14
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,892
    Have you actually looked at the file that you write now? You'll find that the four numbers are in one big string, without separators. Not good.

    As for the other program failing, is the numbers.dat file in a place where it can be found by the program? You expect it to be in the current directory. And since you foolishly limited your path to 15 characters, you won't be able to enter an absolute path. (Use std::string for the filenames!)
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  15. #15
    Registered User
    Join Date
    Dec 2012
    Posts
    9
    Sorry CornedBee, but I am real stuck here! I did look at numbers.dat and created the necessary separators (snippet below). However, in spite of my research at a couple of discussion boards, I am unable to get a handle of how to use std::string that you recommended to be able to open numbers.dat. Sadly, even my C++ book does not address this issue. I know you have already walked me this far, but I will appreciate even more if you give me a clue of what I have to do to use std::string to solve the subject problem. What do I do with std::string in this case?

    BTW, the limitation imposed by use of the 15 characters originated from the source of this problem example - Walter Savitch. I trust, if I find my way around this problem, I will be able to contemplate better ways to solve similar problems in future. Many thanks and sorry for all the trouble!!

    Code:
    #include <fstream>
    #include <string>
    #include <iostream>
    #include <cstdlib>
    using namespace std;
    
    int main()
    {
        int num1, num2, num3, num4;
        //string numbers;
        cout << "Enter the four numbers: " << endl;
        cin >> num1 >> num2 >> num3 >> num4;
        cout << "The numbers are: " << num1 << " "<< num2 << " " << num3 << " " << num4;
        ofstream writer("numbers.dat");
        if(!writer)
        {
            cout << "Error opening file for output" << endl;
            return -1;
        }
        writer << num1 << ", " << num2 <<", " << num3 <<", " << num4 << endl;
        writer.close();
        return 0;
    }

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading data from files
    By heinrichxs in forum C++ Programming
    Replies: 3
    Last Post: 02-07-2011, 12:13 PM
  2. reading data fom files
    By shuo in forum C++ Programming
    Replies: 11
    Last Post: 10-22-2007, 12:24 AM
  3. Trouble Reading Data from Files
    By CConfusion in forum C Programming
    Replies: 11
    Last Post: 04-06-2006, 07:12 PM
  4. Replies: 1
    Last Post: 10-22-2005, 05:28 AM
  5. Reading data from files
    By ChwanRen in forum C Programming
    Replies: 4
    Last Post: 05-06-2003, 07:40 PM

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