My question is how do I add onto my for loop so that when it does its multiple iterations, the variables will overwrite each other?
I am trying to take an input text file with three shares like so:
*Google (GOOG)
522.01 2 100
520.66 1.5 80
Apple (AAPL)
389.27 2 150
401.82 1.8 150
Microsoft (MSFT)
25.06 2.5 100
25.07 2 80*
Then later print/write it onto an output text file.
Now when it runs its iteration 3 times, It only displays stock 1 and its correct numbers, but then wrong numbers and no name for the others. So how would I go about making it so the next iterations will overwrite and print another set of answers?
below is the for section code I have:
for (int x = 1; x <= 3; x++) // for loop to run this part of program 3 times
{
getline(dataIn, stockName);//Gets the whole first line
dataIn >> buyingAMT;//These just store whatever is in the line before every space, and sets it with a name
dataIn >> buyingComm;//So like it takes the characters leading up to the first space and stores it as buyingAMT.
dataIn >> numberBought;
dataIn >> sellingAMT;
dataIn >> sellingComm;
dataIn >> numberSold;
//writing to a file
buyingComm = buyingComm * buyingAMT;//Mathematical Calculations
buyingAMT = buyingAMT * numberBought;
sellingComm = (sellingComm / 100) * numberSold;
sellingComm = sellingComm * sellingAMT;
sellingAMT = sellingAMT * numberSold;
profit = (sellingAMT - sellingComm) - (buyingAMT + buyingComm);
//Displaying the calculated answers
fout << setw(20) << left << stockName;
fout << setprecision(2) << fixed << setw(15) << right << buyingAMT;
fout << setprecision(2) << fixed << setw(15) << right << buyingComm;
fout << setprecision(2) << fixed << setw(15) << right << sellingAMT;
fout << setprecision(2) << fixed << setw(15) << right << sellingComm;
fout << setprecision(2) << fixed << setw(15) << right << profit << endl;
//Storing the results into the overall variables to be used later
/*totalBuyingAMT += buyingAMT;
totalBuyingComm += buyingComm;
totalSellingAMT += sellingAMT;
totalSellingComm += sellingComm;
grandProfit += profit;
*/
}
getline(dataIn, junk);//Cleans the remaining unread data
dataIn.close();//closes the input file, so it cant be read any longer
fout.close();
cout << "congrats you are either now screwed or rich!";
return 1;
}
what I get as output
what i need to get
Variables as long as they are not const can always be re-written or copied. What it looks like from your code there is an issue with how your extracting the text.
dataIn >> buyingAMT;//These just store whatever is in the line before every space, and sets it with a name
dataIn >> buyingComm;//So like it takes the characters leading up to the first space and stores it as buyingAMT.
dataIn >> numberBought;
dataIn >> sellingAMT;
dataIn >> sellingComm;
dataIn >> numberSold;
So what kind of types are dataIn and the other variables here? It seems as though your not splitting the text correctly or don't have a way to do that from dataIn.
This is a small example where one line is taken from stdin (although it can be any stream)
#include <iostream>
#include <string>
int main() {
int i;
std::string input;
for(i=0;i<3;i++)
{
std::cout << "Please give me some input:";
std::cin >> input;
std::cout << "You gave me:" << input << std::endl;
}
}
ofstream fout;//data type used to write the data taken from input file and put it on output file
fout.open(output_File_Name);
if (fout.fail())
{
fout << "Input file not found: " << output_File_Name << endl;
system("pause");
return 0;
}
fout << setw(20) << left;//Setting the labels
fout << "STOCK";
fout << setw(15) << right;
fout << "BUYING AMT";
fout << setw(15) << right;
fout << "BUYING COMM";
fout << setw(15) << right;
fout << "SELLING AMT";
fout << setw(15) << right;
fout << "SELLING COMM";
fout << setw(15) << right;
fout << "PROFIT" << endl;
Related
Okay so me and a few colleagues were working on an assignment for class. I completed it to my fullest extent; however, there is one thing that neither I nor any of my colleagues could fix. I searched for hours online but couldn't fine the answer I needed.
The first line that is printed after the data is read from the file is always shifted 1 space to the right. That is my only problem. The string is not shifted, but everything is. We checked for spaces, tabs, and extra symbols, we tried switching up the file we were reading from all to achieve nothing. I would really appreciate it if someone could point out what is wrong with my program. Thanks in advance!
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
ifstream inputFile;
cout << "Please enter the file you would like to open: ";
string filename;
cin >> filename;
inputFile.open(filename);
if(inputFile.fail())
{
cout << "Error: File failed to open or was not found..." << endl;
}
else
{
cout << "File opened" << endl;
string land;
double price, min, max, total, average, count;
count = 0;
min = 0;
max = 0;
total = 0;
while(inputFile.good())
{
getline(inputFile, land, '\t');
inputFile >> price;
cout << fixed << setprecision(2) << setw(40) << left << land << right << "$ " << price;
if(count == 0)
{
max = price;
min = price;
}
if(price > max)
{
max = price;
}
if(price < min)
{
min = price;
}
total += price;
count++;
}
inputFile.close();
average = total / count;
cout << endl << endl;
cout << setw(43) << "Average Price = $ " << average << endl;
cout << setw(43) << "Highest Price = $ " << max << endl;
cout << setw(43) << " Lowest Price = $ " << min << endl;
}
return 0;
}
What doesn't make sense to me is that it is a loop, so why is only the first one being shifted?
This is what was on the file I was using
Landmark 1258
Creekside 1840
Parkside 1575
Gallatyn Walk 1710
Oak Mill 1185
Cutler's Ridge 1495
Prairie Creek Cottages 1987
Waterview Mills 1505
Canterbury Courts 1300
Breckinridge Point 1205
The Junction 1699
The words and numbers should all be separated with a tab.
The Image shows the output I was always given.
The difference is that from the first line, variable "land" is "Landmark" while all the others have the \n in front of the name, taken from the previous line, ie "\nCreekside", "\nParkside" etc.
You could just delete the \n from the string name and then add it at the end of your std::cout:
while (inputFile.good())
{
getline(inputFile, land, '\t');
if (land[0] == '\n')
{
land.erase(0, 1);
}
inputFile >> price;
cout << fixed << setprecision(2) << setw(40) << left << land << right << "$ " << price << endl;
Now the outcome is formatted correctly!
It's an illusion. The first line is spaced correctly. Every other value you read in with getline will include a \n character, which is where inputFile >> price left off.
A quick fix is to ignore all characters to the end of line after reading price (requires you to include <limits>):
getline(inputFile, land, '\t');
inputFile >> price;
inputFile.ignore( numeric_limits<streamsize>::max(), '\n' );
cout << setw(40) << left << land << right << "$ " << price << endl;
A better approach is to always read lines in the first place. This is also a more correct loop condition, and a practise you should get into (this version uses <sstream>):
string line;
while( getline( inputFile, line ) )
{
istringstream line_ss( line );
if( getline( line_ss, land, '\t' ) >> price )
{
cout << setw(40) << left << land << right << "$ " << price << endl;
}
}
This is the code I have written so far to calculate the odds of profiting from playing lottery scratchers. I have to prompt the user for out output file name (output.txt), where a formatted table with the results will be written. So far my program will output the results, but not in an output file. I am not really sure how to do that or where that will go in my code.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
// Declaring variables
int lowestAmountOfProfit;
char filename[]="scratcher.txt";
string gameName;
int CostOfTicket, NumberOfPrizes;
int PrizeValue, NumberOfTickets, TicketsNotClaimed;
double RemainingTickets;
double RemainingTicketsForProfit;
double odds;
// The program will ask the user to enter the lowest amount they would like to
// profit when playing the lottery.
cout << "Enter the lowest dollar amount that you would like to profit: "
cin >> lowestAmountOfProfit;
cout << "Enter the output file name: "
cout << "Generating report..."
//open input file
ifstream fin;
fin.open(filename);
//if input file does not exist
if (!fin)
{
// If the input file cannot be found.
cout << "Input file does not exist." << endl;
return 0;
}
//How the output displace will be formatted.
cout << left << setw(25) << "Game" << setw(10) << "Cost" << setw (10) << "Odds" << endl;
cout << "-----------------------------------------------" << endl;
// Reads the name of the game
while (getline(fin, gameName))
{
fin >> CostOfTicket; // Reads the cost of ticket
fin >> NumberOfPrizes; // Reads the number of prizes
RemainingTickets = 0;
RemainingTicketsForProfit = 0;
for (int i = 0; i < NumberOfPrizes; i++)
{
fin >> PrizeValue; // Reads the prize value
fin >> NumberOfTickets; // Reads the total number of tickets
fin >> TicketsNotClaimed; // Reads number tickets not claimed
//regardless of prize value*/
// The following line computes the running sum of the number of tickets remaining for that game.
RemainingTicketsForProfit = RemainingTicketsForProfit + TicketsNotClaimed;
// The next line with compute a sum of the number of remaining tickets where the user would profit.
if (PrizeValue > lowestAmountOfProfit)
{
RemainingTickets = RemainingTickets + TicketsNotClaimed;
}
}
// Tells program what to do if there are zero remaining tickets
if (RemainingTickets==0)
{
// Formats the output
cout << left << setw(25) << gameName << setw (2) << "$" << CostOfTicket << right << setw(15) << "Not possible" << endl;
}
else
{
// Tells the program to calculate the odds
odds = RemainingTicketsForProfit / RemainingTickets;
cout << left << setw(25) << gameName << setw (2) << "$" << CostOfTicket << right << setw(15) << "1 in " << setprecision(2) << fixed << odds << endl;
}
// Read the blank line
string blankLine;
fin >> blankLine;
}
// Close the input file
fin.close();
return 0;
}
You can output to a file by just declaring it as a ofstream and then basically using it as a cout. Like so:
ofstream outputFile;
outputFile.open("filename.txt");
cout << "Enter the first number: ";
cin >> num1;
outputFile << num1 << endl;
outputFile.close();
I currently have a Vector class that is of template class, to store some stock objects. Eg. Vector<Stock> vecA;
In my assignment, it is a requirement to use a Binary Search Tree, perform an inorderTraversal() on it so it gets sorted, then do some processes with it in the Main()
In attempt to "hide" the traverse process from the user, and to store the sorted data after traversing the binary search tree, I'm changing the cout << p->info part to outputting the traversed data into an output file.
Which means:
if (p != NULL)
{
inorder(p->lLink);
cout << (p->info) << endl; //changed to vecA.Push_back(p->info);
inorder(p->rLink);
}
However, it is not pushing the items from the nodes into my vector the way I wished it would. It's technically working, I am able to Print() out all the rows of the data neatly, one after another, but when I do a Vector.getLength(), it shows that there's only 1 row.
The issue here is, when the Vector only has 1 row (but weirdly contains all the items I have and displays row after row), I can't work with this Vector, as most of the processes involve for-loops.
Please advise, I'm suspecting a problem with my inorder() method or something. Maybe it's the way a BST outputs data etc. I'm very new to BST and I'm not given much time to complete this assignment.
Here's my code for my inorder() function
template <class elemType>
void binaryTreeType<elemType>::inorder(nodeType<elemType> *p) const
{
Vector<Stock> bstData;
ofstream of("output.csv");
of << fixed << showpoint << setprecision(2);
if (p != NULL)
{
inorder(p->lLink);
bstData.Push_back(p->info);
inorder(p->rLink);
}
//Below is a for-loop that I was planning to use to get the traversed data
//from the Vector into an output file so I can access the traversed data
//through reading an output file from my Main() function
for(int i = 0; i < bstData.getLength(); i++)
{
cout << "bstData data at " << i << ": " << bstData.at(i) << endl;
//above statement is to check if i did an increment
cout << "bstData length is: " << bstData.getLength() << endl;
//above statement is to check my vector's length
//the following statement is to output data from vector into a .csv file
of << bstData.at(i).d1.getDay() << "/" << bstData.at(i).d1.getMonth() << "/" << bstData.at(i).d1.getYear() << "," << setw(2) << setfill('0') << bstData.at(i).t1.getHour() << ":" << setw(2) << setfill('0') << bstData.at(i).t1.getMin() << ":" << setw(2) << setfill('0') << bstData.at(i).t1.getSec() << "," << bstData.at(i).getPrice() << "," << bstData.at(i).getVolume() << "," << bstData.at(i).getValue() << endl;
cout << "i is now at: " << i << endl; //check i again
}
of.close();
} //close inorder()
Following is the output when I run my program:
P.S: I cannot post images so please kindly refer to this link for the image!!
http://i132.photobucket.com/albums/q28/LoveSHE911/Screen%20Shot%202015-11-17%20at%205.05.48%20am_zpstldxxags.png
Following is the output when I run bstData.Print() to check the contents of the vector.
http://i132.photobucket.com/albums/q28/LoveSHE911/Screen%20Shot%202015-11-17%20at%205.07.27%20am_zpsrqqo8kzb.png
Please kindly advise and help, I'm lost!
EDITS: Thanks to #Mykola, I've solved my issue as above, but one closely related problem occurred.
After performing inorderTraversal() in my main(), I wanted to do an ifstream inFile("output.csv") and a while (inFile >> dd >> c >> mm >> c >> yy >> ...) to read the file's data, create a stock object with the data, and push_back into an existing vector. Code as follows.
ifstream inputfile("output.csv"); //open user chosen data file
//load traversed data from output file output.csv into vAll
while (inputfile >> dd >> c >> mm >> c >> yy >> hh >> c >> mn >> c >> ss >> ch1 >> ch2 >> pr >> vl >> tp)
{ //check if there's remaining data in input file
Stock stk2(dd, mm, yy, hh, mn, ss, ch1, ch2, pr, vl, tp);
//if there's still remaining data, create new stock object
vAll.Push_back(stk2); //Insert stock object into vector
}
cout << vAll.getLength() << endl; //check vector length
However, vAll.getLength() returns 0. Is there an obvious mistake I'm not seeing?
You must rebuild your function to pass the storage target with node pointer. It means
void binaryTreeType<elemType>::inorder(nodeType<elemType> *p, Vector<Stock>& storage) const
so entire code will have one more function
template <class elemType>
void binaryTreeType<elemType>::inorder(nodeType<elemType> *p) const
{
Vector<Stock> bstData;
ofstream of("output.csv");
of << fixed << showpoint << setprecision(2);
inorder(p, bstData); // fill bstData recursively
for(int i = 0; i < bstData.getLength(); i++)
{
cout << "bstData data at " << i << ": " << bstData.at(i) << endl;
//above statement is to check if i did an increment
cout << "bstData length is: " << bstData.getLength() << endl;
//above statement is to check my vector's length
//the following statement is to output data from vector into a .csv file
of << bstData.at(i).d1.getDay() << "/" << bstData.at(i).d1.getMonth() << "/" << bstData.at(i).d1.getYear() << "," << setw(2) << setfill('0') << bstData.at(i).t1.getHour() << ":" << setw(2) << setfill('0') << bstData.at(i).t1.getMin() << ":" << setw(2) << setfill('0') << bstData.at(i).t1.getSec() << "," << bstData.at(i).getPrice() << "," << bstData.at(i).getVolume() << "," << bstData.at(i).getValue() << endl;
cout << "i is now at: " << i << endl; //check i again
}
of.close();
} //close inorder()
and main recursive function
template <class elemType>
void binaryTreeType<elemType>::inorder(nodeType<elemType> *p, Vector<Stock>& storage) const
{
if (p != NULL)
{
inorder(p->lLink, storage); // Fill storage with left values
storage.Push_back(p->info); // Add current value to storage (actualy bstData).
inorder(p->rLink, storage); // Fill storage with right values
}
} //close inorder()
To load your data from file try to do that
while (inputFile.good()) // if stream is good
{
inputfile >> dd >> c >> mm >> c >> yy >> hh >> c >> mn >> c >> ss >> ch1 >> ch2 >> pr >> vl >> tp;
//check if there's remaining data in input file
Stock stk2(dd, mm, yy, hh, mn, ss, ch1, ch2, pr, vl, tp);
//if there's still remaining data, create new stock object
vAll.Push_back(stk2); //Insert stock object into vector
}
cout << vAll.getLength() << endl; //check vector length
I think you also must rewrite your reading operation
inputfile >> dd >> c >> mm >> c >> yy >> hh >> c >> mn >> c >> ss >> ch1 >> ch2 >> pr >> vl >> tp;
istream does not support formatted input so you must probably parse data in different way or use fscanf wich support this feature.
I'm having some trouble here. I have a file that looks like this (here's a snippet)
Sophia F 22158
Emma F 20791
Isabella F 18931
Jacob M 18899
Mason M 18856
Ethan M 17547
and I want to put each name, and the name's respective number into seperate vectors. For example, I would have 4 vectors:
1 for women's names and 1 for women's numbers, and the same for men's and men's numbers. (so 4 total)
I have this code, which will go through the file and pull out these elements and put them in vectors.
for (int i = 0; i < numTimes; i++) {
getline (inputFile, inputLine);
ss.str(inputLine); //ss is a string stream
ss >> name >> gender >> popularity;
if (gender == 'M') {
mNames[i] = name;
mFrequency[i] = popularity;
} else if (gender == 'F') {
fNames[i] = name;
fFrequency[i] = popularity;
}
ss.clear();
}
and I use this method to print it out:
cout << counter << " Most Popular Baby Names" << endl << endl;
cout << left << setw(15) << "Girls" ;
cout << right << setw(9) << "Frequency" <<" ";
cout << left << setw(15) << "Boys";
cout << right << setw(9) << "Frequency" << endl;
for (int i = 0; i < counter; i ++) {
cout << left << setw(15) << fNames[i] ;
cout << right << setw(9) << fFreq[i] <<" ";
cout << left << setw(15) << mNames[i];
cout << right << setw(9) << mFreq[i] << endl;
{
but then I get this output:
http://i.stack.imgur.com/2x0ta.png
But I would like for it to be like this:
http://i.stack.imgur.com/OSIX9.png
So I'm thinking I either need to go through before I print and remove all the whitespace/0's in these vectors, or I need to check while I'm printing out. Does anyone have any pointers?
Solved, thanks guys.
I used two separate while loops, one for each set of arrays. In between them I reset the ifstream back to the beginning. This way, it goes through until each vector has 5 non-zero elements.
I am new to programming and trying to teach myself but my counter is displaying one more than it should. it should be displaying 22, but it is displaying 23.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
//Main and variable data type initializing
void main()
{ float c,l,x,y,z;
int count;
string input, output;
string finput, foutput;
fstream i,o; //i = input file; o = output file;
//Getting the name of the files
cout << "XZY Multiply Program\n" << endl;
cout << "Enter the input file name: c:/";
cin >> input;
cout << "Enter the output file name: c:/";
cin >> output;
//inserts the beginning of the file and file extension.
finput = "c:/" + input;
foutput = "c:/" + output;
//Opens files
i.open(finput.data(),ios::in);
o.open(foutput.data(),ios::out);
//Initialize count and sum of variables
count = 0;
x=0;
y=0;
z=0;
//loop through input file
while(!i.eof() && !o.eof())
{ count++;
if (i.good() && o.good())
{
i >> c;
i >> l;
o << fixed << showpoint << setprecision(4);
o << setw(7) << c;
o << setprecision(2);
o << setw(9) << l;
o << setprecision(3);
o << setw(10) << (l*c) << endl;
// Adds columns
x = x+c;
y = y+l;
z = z+(l*c);
}
else
{
cout << "no good";
}
}
i.close();
o.close();
//Display the output of the counter and Sums of columns
cout << fixed << showpoint << setprecision(2);
cout << "\n" << count << " lines in file " << endl;
cout << "X sum = " << setw(8) << right << x << endl;
cout << "Y sum = " << setw(8) << right << y << endl;
cout << "Z sum = " << setw(8) << right << z << endl;
}
7.2830 84.40
9.1327 124.02
7.2619 133.16
6.2527 43.96
4.2160 24.08
5.2724 57.80
5.2025 73.89
-9.9500 80.53
0.2790 -12.43
2.2115 3.37
3.1222 13.63
16.2413 223.01
-4.2026 33.78
-7.1914 42.89
4.1417 53.42
6.1714 61.66
9.2516 73.68
15.2419 383.66
6.2715 93.53
-3.2016 3.46
12.2013 213.63
3.1824 23.85
Using .eof() or .good() as a loop condition almost always produces buggy code, as it does in this case.
Rather, perform the input and check its result in the loop condition, like so:
while(i >> c >> l)
{ count++;
o << fixed << showpoint << setprecision(4);
o << setw(7) << c;
...
References:
Why is iostream::eof inside a loop condition considered wrong?
http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5
I assume that after reading the last number from the input file the end of file has not been seen, yet. Try adding
if (!i.good()) break;
after each input statement (>>) to prevent the loop body to be executed after a failed input.