//project.cpp                compiles
//Need to create an input file of recently shipped music CD's. 
//The file should consist of the name of the album, quantity shipped and price.
// Since we do not know how many CD's have been shipped, keep reading the file 
//until all CD's have been read in. Keep track of both the number of different 
//CDs as well as the total number of CDs shipped. Your program should determine 
//the value of each CD shipped (quantity * price). Create an array to hold this 
//value and print out all values in the array.  

#include <iostream>               
#include <fstream.h>
#include <stdlib.h>
using namespace std;
int main()

{
      //if is digit peek
//see isstream.peek
float CD[5];  
char album[22];     
int num;
float totqty =0, qty=0, val=0, price=0;
ifstream incd;
ofstream outcd;

incd.open("incd.txt");
outcd.open("outcd.txt");

 if (incd.fail())
  {
     cout<<"Output file doesn't exist!";
     exit(1);
  }
    
  
    for (num=0; num<5; num++)    
    {
      incd.getline(album,22);  
      incd>>qty;                   //reading 5 files, has name only of 1st album, all values 0
      incd>>price;
      val = qty * price; 
      // cout<<val<<endl;         //when test with this, prints 5 zeroes
      outcd<<"The value of "<<album<<"CD is: "<<val<<endl;  //putting blank spaces in + putting 0
      }                    //how will do cout for each album if not in loop
      totqty = totqty + qty;            //total CDs shipped
      //cout<<totqty<<endl;              //when test with this, prints 0
   
    val = 0;
    qty = 0;
    price = 0;
             
  outcd<<"The total CDs shipped is: "<<totqty<<endl; //should be 54
   
system("PAUSE");
incd.close();
	return 0;
}

<< moderator edit: added [code][/code] tags >>

:?:

Dani AI

Generated

— the symptom you reported (only the first album name showing, then zeros) is the classic result of mixing formatted extraction (operator>>) with line-based reads (getline) and using a fixed-count loop. 's prompt "What's it doing/not doing?" is on point: the newline left in the stream after reading numbers makes the next getline return an empty title, then the following numeric extraction fails and yields zeros. Other issues: totals are updated outside the read loop, the file-open error message checks the wrong stream, and a fixed-size array is brittle.

Simple, reliable fixes

  • Read album titles with std::getline into std::string (no fixed-size char buffer).
  • Read the numeric data as a separate line and parse it with std::istringstream (this avoids leftover-newline problems), or after using >> call ignore(...) before getline.
  • Loop until EOF (while getline succeeds) instead of for (i = 0; i < 5).
  • Accumulate totals inside the loop and store per-record values in a std::vector<double>.
  • Check input and output opens separately and print which one failed.

Example (robust, handles "title on one line, qty price on next" and also "title and numbers on same line"):

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

int main() {
    std::ifstream fin("data.txt");
    std::ofstream fout("results.txt");
    if (!fin) { std::cerr << "Cannot open input file\n"; return 1; }
    if (!fout) { std::cerr << "Cannot open output file\n"; return 1; }

    std::string album;
    std::vector<double> values;
    int totalQty = 0;

    while (std::getline(fin, album)) {
        if (album.empty()) continue;
        std::string nums;
        std::getline(fin, nums); // read next line (expected: qty price)
        std::istringstream iss(nums.empty() ? album : nums);
        int qty = 0; double price = 0.0;
        if (!(iss >> qty >> price)) {
            fout << "Bad record (skipped): " << album << '\n';
            continue;
        }
        double val = qty * price;
        values.push_back(val);
        totalQty += qty;
        fout << "Value of \"" << album << "\" CD is: " << val << '\n';
    }
    fout << "Total CDs shipped: " << totalQty << '\n';
}

Troubleshooting notes: add diagnostic prints (quote the album when writing) to detect empty titles, validate stream state after extractions, and prefer std::vector over fixed arrays so the program adapts to any file length.

What's it doing/not doing?

Posting code is one thing, but if you describe what is supposed to happen, someone can help you target what the problem is.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.