CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12

Hybrid View

  1. #1
    Join Date
    Jun 2017
    Location
    Berkeley CA
    Posts
    19

    Question about writing programs with file input/output

    Hello all,
    I just finished chapter 3 (input/output) in my C++ class.
    There is an assignment in the back of the book which reads:

    Consider the following incomplete C++ program:
    Code:
    #include <iostream>
    int main()
    {
    ...
    }
    a. write a statement that includes the header files stream, string, and iomanip in this program.
    b. Write statements that declare inFile to be an upstream variable and outFile to be an of stream variable.
    c. The program will read data from the file inData.txt and write output to the file outData.txt. Write statements to open both of these files, associate inFile with inData.txt, and associate outFile with outData.txt
    d. suppose that the file inData.txt contains the following data:
    Giselle Robinson Accounting
    5600 5 30
    240 9
    75 1.5
    The first line contains a persons first name, last name, and the department the person works in. In the second line, the first number represents the monthly gross salary, the bonus (as a percent), and the taxes (as a percent)/ The third line contains the distance traveled and the traveling time. The fourth line contains the number of coffee cups sold and the cost of each coffee cup. Write statements so that after the program executes, the contents of the file outData.txt are shown below. If necessary, declare additional variables. Your statements would be general enough so that if the content of the input file changes and the program is run again (without editing and recompiling), it outputs the appropriate results.

    Name: Giselle Robinson, Department: Accounting
    Monthly Gross Salary: $5600.00, Monthly Bonus: 5.00 %, Taxes: 30.00 % Paycheck: $4116.00

    Distance Traveled: 450.00 miles, Traveling Time: 9.00 hours
    Average Speed: 50.00 Miles per hour

    Number of Coffee Cups Sold: 75, Cost: $1.50 per cup
    Sales Amount=$112.50

    e. write statements that close the input and output files
    f. write a C++ program that tests the statements in part 1 through e.

    Ok so here is my question, I am unclear on how to test this program
    Are we supposed to write a program which prompts a user to input this info? if so wouldn't we be using cin/cout statements and not outFile/inFile statements? The text book told me to follow a previous example so I will attach my .cpp file.

    I have faith in myself that I could write a program that prompts a user to enter name, department worked salary and all other information, execute and look exactly like part d of above question, however I feel as though that is not what the question is asking...
    any help would be appreciated

    Thanks
    Will
    in case my attachment does not work here is the code:

    Code:
    //  main.cpp
    //  practice
    //
    //  Created by William Fantin on 6/26/17.
    //  Copyright © 2017 William All rights reserved.
    //
    
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <iomanip>
    
    
    
    using namespace std;
    
    int main()
    {
        
        ifstream inFile;
        ofstream outFile;
        double monthlyGrossSalary,bonusAsPercent,taxesAsPercent,distanceTraveled,travelingTime,averageSpeed,payCheck,numberOfCoffeeCupsSold,costPerCup,salesAmount;
        string firstName;
        string lastName;
        string departmentWorked;
        
    
        inFile.open("inData.txt");
        outFile.open("outData.txt");
        
        outFile<<fixed<<showpoint;
        outFile<<setprecision(2);
        cout<< "Processing Data" << endl;
        
        inFile>> firstName>> lastName;
        outFile<<"Name= "<< firstName << " " << lastName << endl;
        inFile>> departmentWorked;
        outFile<<"Department= "<< departmentWorked << endl;
        //gets you first line which is name followed by department worked
        
        inFile>>monthlyGrossSalary;
        outFile<< "Monthly Gross Salary= "<<monthlyGrossSalary<<endl;
        inFile>>bonusAsPercent;
        outFile<< "Monthly Bonus= "<<bonusAsPercent<<endl;
        inFile>> taxesAsPercent;
        outFile<< "Taxes= "<<taxesAsPercent<<endl;
        inFile>> payCheck;
        outFile<< "Paycheck= "<< payCheck<<endl;
        //next line of data inputted
        
        
        inFile>>distanceTraveled;
        outFile<<"Distance Traveled= "<<distanceTraveled<< endl;
        inFile>>travelingTime;
        outFile<< "Traveling Time= "<<travelingTime<< endl;
        inFile>>averageSpeed;
        outFile<< "Average Speed= " << averageSpeed<< endl;
        //next line of data inputted
        
        inFile>>numberOfCoffeeCupsSold;
        outFile<<"Number Of Coffee Cups Sold= "<<numberOfCoffeeCupsSold<<endl;
        inFile>>costPerCup;
        outFile<< "Cost per cup= "<<costPerCup<< endl;
        inFile>>salesAmount;
        outFile<<"Sales Amount= "<<salesAmount<<endl;
        
        inFile.close();
        outFile.close();
        return 0;
         
    }
    Attached Files Attached Files
    Last edited by 2kaud; June 30th, 2017 at 02:44 AM. Reason: Added code tags

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: Question about writing programs with file input/output

    When posting code, please use code tags so that the code is readable. Go Advanced, select the formatted code and click '#'.

    inData.txt contains the following data:
    Giselle Robinson Accounting
    5600 5 30
    240 9
    75 1.5
    You need to create the inData.txt file yourself that contains the required data (write another c++ program?). This is then used as input to the program as required.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  3. #3
    Join Date
    Jun 2017
    Location
    Berkeley CA
    Posts
    19

    Re: Question about writing programs with file input/output

    Hello Kaud! Thanks for the reply!

    So I spoke with my teacher and she showed us how to make a .txt file so now I know how to do that.
    I am a little confused about your directions on how to upload my code.. so when I post my code as an attachment I also need to go into the advanced settings and hit # for code tags? what is a code tag?

    unfortunately even with my .txt file my code is still creating a file that has all blanks for names and all 0's for numbers but at least I know how to insert a .txt file into my code now!!

    Thanks in advanced!
    Will

  4. #4
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: Question about writing programs with file input/output

    The first issue with the code as posted in post #1 is here

    Code:
    inFile>> payCheck;
    outFile<< "Paycheck= "<< payCheck<<endl;
    payCheck is not a value to be read from the file. It is a value that has to be calculated from the data already read. What you are reading as payCheck is actually the distance travelled.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  5. #5
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: Question about writing programs with file input/output

    what is a code tag?
    A code tag is a special tag that identifies the text between them as code so that it is formatted properly. Code tags start with
    [ c o d e ] (without spaces) and end with
    [ / c o d e ] without spaces

    so without the code tags
    #include <iostream>
    int main()
    {
    ...
    }
    becomes with code tags
    Code:
    #include <iostream>
    int main()
    {
    ...
    }
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  6. #6
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: Question about writing programs with file input/output

    creating a file that has all blanks for names and all 0's for numbers
    This may be because the program can't find the required input file and there's no error tests that detect and report this. On my system the program as posted does produce an output file - but with wrong contents!

    A better way to open the files would be
    Code:
    	const string infilnam = "inData.txt";
    	const string outfilnam = "outData.txt";
    
    
    	ifstream inFile(infilnam);
    	ofstream outFile(outfilnam);
    
    	if (!inFile.is_open()) {
    		cout << "Cannot open input file " << infilnam << endl;
    		return 1;
    	}
    
    	if (!outFile.is_open()) {
    		cout << "Cannot open output file " << outfilnam << endl;
    		return 2;
    	}
    
    	outFile << fixed << showpoint;
    	outFile << setprecision(2);
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  7. #7
    Join Date
    Jun 2017
    Location
    Berkeley CA
    Posts
    19

    Re: Question about writing programs with file input/output

    Ok, I just now have time to work on this, I am going to try to write another very basic file and try to reference a file and see if it can work. Ill get back to you. My teacher was telling me it might be the way i was referencing the file, since I'm using Xcode she was saying you have to reference the entire pathway, which I did and still got incorrect results, well no results. Get back to you soon.
    Thanks

  8. #8
    Join Date
    Jun 2017
    Location
    Berkeley CA
    Posts
    19

    Re: Question about writing programs with file input/output

    Ok so not sure, but what seems to be happening is that my outFile is created and this changes the inFile to read exactly what was in my outFile statement.
    for example:
    my .txt file that I created for my code to reference reads something like: Giselle Robinson
    my inFile statement is: inFile>>firstName>>lastName;
    followed by: outFile<<"Student name: "<<firstName<<" "<<lastName<<endl;

    what seems to be happening is the outFile that is created just has Student name: in it. And when I go to my inFile which i manually inserted under my main.cpp file it also reads Student name:

    I will try to attach my code with code tags this time since I simplified the entire code instead of trying the whole program just starting out with name.

    Code:
    #include <iostream>
    #include <fstream>
    #include <iomanip>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        //Declare variables;
        ifstream inFile; //input file stream variable
        ofstream outFile; //output file stream variableurn 0;
        
        string firstName;
        string lastName;
        
        inFile.open("/Users/williamfantin/Desktop/name.txt");
        outFile.open("/Users/williamfantin/Desktop/name.txt");
        
        inFile >> firstName >> lastName;
        outFile << "Student name: " << firstName << " " << lastName<<endl;
        
        inFile.close();
        outFile.close();
        return 0;
    }

  9. #9
    Join Date
    Jun 2017
    Location
    Berkeley CA
    Posts
    19

    Re: Question about writing programs with file input/output

    my .txt file literally just says: Giselle Robinson
    Am I not referencing it correctly?
    Is my code wrong?
    Not quite sure, will update you guys if I figure anything out

  10. #10
    Join Date
    Jun 2017
    Location
    Berkeley CA
    Posts
    19

    Re: Question about writing programs with file input/output

    Ok weird thing just happened, I was doing some research online about referencing .txt files (I assume it would pertain to any files as well) and what I did on x-code was go to file, add file, new folder, create a folder titled "resources", I assume I could have called it anything I wanted. Drag and drop my .txt file into the resources folder (which was underneath my main.cpp folder, copy the full path from my .txt file which was in the resources folder, paste that into my inFile.open(pasted full pathway here) and ran the program). This worked and created another .txt folder with the proper info, I will attach code below

    Code:
    #include <iostream>
    #include <fstream>
    #include <iomanip>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        //Declare variables;
        ifstream inFile; //input file stream variable
        ofstream outFile; //output file stream variableurn 0;
        
        string firstName;
        string lastName;
        
        inFile.open("/Users/williamfantin/Desktop/clueless2/clueless2/Resources/Yes.txt");
        outFile.open("/Users/williamfantin/Desktop/clueless2/clueless2/Resources/Yes2.txt");
        
        inFile>>firstName>>lastName;
        outFile << "Student name= " << firstName << " " << lastName<<endl;
        
        inFile.close();
        outFile.close();
        return 0;
    }
    As you can see in my outFile.open i changed the name to Yes2.txt, this then created the file labeled Yes2.txt with the output Student Name= Giselle Robinson.

    I have no idea what I just did or why it was not working before, but at least I can make it produce the results I want... I will attach a screenshot of what I am seeing in the interface of Xcode so you can see where exactly my "resources" folder is.Name:  Screen Shot 2017-07-02 at 6.09.57 PM.jpg
Views: 2172
Size:  15.9 KB

  11. #11
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: Question about writing programs with file input/output

    Code:
        inFile.open("/Users/williamfantin/Desktop/name.txt");
        outFile.open("/Users/williamfantin/Desktop/name.txt");
    The issue here is that infIle and outFile use the same file name. As outfile is of type ofstream, the output file is cleared when the file is opened which as it is the same as the infile means that the infile is cleared!

    Code:
    inFile.open("/Users/williamfantin/Desktop/clueless2/clueless2/Resources/Yes.txt");
    outFile.open("/Users/williamfantin/Desktop/clueless2/clueless2/Resources/Yes2.txt");
    This is ok because the infile and outfile names are different.

    I don't know or use xcode, but IMO having the files listed under resources has no bearing on the issue. The problem was having infile and outfile with the same name.
    Last edited by 2kaud; July 3rd, 2017 at 02:48 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  12. #12
    Join Date
    Jun 2017
    Location
    Berkeley CA
    Posts
    19

    Re: Question about writing programs with file input/output

    Ok this worked without the resources folder like you said. They just needed to be named differently!!!
    Thanks!!

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