Why is the first line shifted one space to the right? - c++

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;
}
}

Related

For loop that allows for variables to overwrite each other

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;

I am designing a programming that calculates the odds of profiting if you played several scratch- off lottery games

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();

C++ fstream building but not running

I'm building a program for my class the requires us to import data from a .txt file and the item names/ prices will be used to calculate saltes tax and grand total. My teacher put this up as an example, but I can't get it to run.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{ // Beginning of main function
string name;
ifstream data_in;
ofstream data_out;
int cnt=0;
int number;
struct Item
{
int item_n;
char disc[50];
float price;
};
Item store[999];
data_in.open("cost.txt");
data_out.open("file_out.txt");
while(!data_in.eof())
{
//cout << "Enter in the item number: ";
data_in >> store[cnt].item_n;
//cout << "Enter in the description for item number " << store[cnt].item_n << ": ";
data_in >> store[cnt].disc;
//cout << "Enter in the price for the " << store[cnt].disc << ": $";
data_in >> store[cnt].price;
cnt++;
}
cout << endl << endl;
number = cnt;
for (cnt=0; cnt<number; cnt++)
{
name = store[cnt].disc;
cout << setw(5) << store[cnt].item_n << " " << store[cnt].disc << setw(16-name.length()) << "$" << setw(9) << store[cnt].price << endl;
}
for (cnt=0; cnt<number; cnt++)
{
name = store[cnt].disc;
data_out << setw(5) << store[cnt].item_n << " " << store[cnt].disc << setw(16-name.length()) << "$" << setw(9) << store[cnt].price << endl;
}
return 0;
}
And this is the information in the cost.txt file
Books 45.01
Pens 21.03
Pencils 10.90
Hats 50.00
Caps 800.00
Food 1.00
The code you've written reads three things for each Item: the item number, the description, and price.
The sample data file you shown contains only two things for each item: what looks to be a description, and a price.
The expected data format does not match the contents of the input file. This code will never work, as is. One or the other is wrong. Plus all the other problems with the code, as mentioned in the comments.
Try the following changes, the rest of your code seems to work:
data_in.open("cost.txt");
data_out.open("file_out.txt");
if (!data_in.is_open() || !data_out.is_open()) //Test if files opened correctly...
{
cout << "Failed to open a file!\n";
return 1;
}
float SalesTotal = 0;
while(true)
{
if (!(data_in >> store[cnt].disc))
{
//Failed to read first element in this record - could be eof or format error
if (data_in.eof())
break; //eof - all records read.
cout << "Format error first field\n";
return 1; //format error on first field.
}
if (!(data_in >> store[cnt].price))
{
cout << "Format error second field\n";
return 2; //format error on second field.
}
store[cnt].item_n = cnt + 1; //Item number is not a field in your file, use the counter...
SalesTotal += store[cnt].price;
cnt++;
}
if (!cnt)
{
cout << "No records read\n";
return 3; //No valid records read.
}
float GrandTotal = ((SalesTotal / 100) * 6) + SalesTotal;
cout << "Sales total: " << SalesTotal << " Grand total:" << GrandTotal << "\n";

C++ Cash Register Program Not using <string>

I have to write a program without using strings . Here is my code :
#include <iostream>
#include <iomanip>
using namespace std;
struct product
{
char productName[100];
double productPrice = 0;
};
const int MAX_CHAR = 101;
const int MAX_ITEM = 100;
int main()
{
product item[MAX_ITEM];
double total = 0;
int count = 0;
for (int i = 0; i < MAX_ITEM; i++)
{
cout << "Please , enter the product name(for checkout type -1) : ";
cin.get(item[i].productName, MAX_CHAR, '\n');
cin.ignore(100, '\n');
if (strcmp(item[i].productName, "-1") == 0 ) {
break;
}
else {
count++;
cout << "Please , enter the price for " << item[i].productName << " : $";
cin >> item[i].productPrice;
cin.ignore(100, '\n');
total += item[i].productPrice;
cout << endl << "Product entered : " << item[i].productName << " " << "$"
<< fixed << setprecision(2) <<item[i].productPrice << endl;
cout << "Total : $" << total << endl << endl;
}
}
cout << endl << "###############";
cout << endl << "Your Receipt : " << endl << endl;
for (int i = 0; i < count; i++) {
cout << item[i].productName << " $" << fixed << setprecision(2) << item[i].productPrice << endl;
}
cout << endl << "Total : $" << total;
cout << endl << "###############";
getchar();
getchar();
return 0;
}
I have a couple questions :
Why does the program crash if I don't use cin.ignore(100, '\n'); after cin >> item[i].productPrice; ? It's just cin without any condition, so it should not leave a new line char in input stream?
How can I check if the price doesn't contain incorrect input (so it has only decimal or floating point numbers) ?
How can I check if the name contains chars and numbers which are >0 (except -1) ?
Is it better to use cin.getline in this case ?
cin is an istream, so it should leave the newline char in the stream if you use cin.get(). I haven't tested if this is the cause of your crash but it sounds like this could give you problems.
chars are just numbers. A . is 46, the digit characters are from 48 through 57. You could read your price input into a buffer and check if you read any char that does not have one of your desired values. If you find an unwanted char, you can decide if you want to repeat the input, ignore this item or exit the program.
In your else branch, check if the first character of productName is a '-'. That way, you already ensured that productName is not -1.
cin.getline() discards the newline character, so you could avoid the use of cin.ignore().

Why won't this piece of my code write to file

I am developing a C++ banking system.
I am able to get the float, newbal, values correctly and when I try to write to file, there is no data in the file.
else if (x == 2)
{
cout << "You have selected option number 2. Deposit.\n";
cout << "Please enter you account ID: ";
cin >> ID;
file.open("C:\\Users\\Raggulddon\\Desktop\\C++ supplement\\Cust_" + ID + ".dat", ios:: in | ios::out | ios::binary);
if (!file)
{
cout << "Sorry the requested account could not be located.\n";
}
else
{
file >> firstname >> lastname;
cout << endl << firstname << " " << lastname << endl;
cout << "-----------------------------------\n";
string line;
while (getline(file, line))
{
// stringstream the getline for line string in file
istringstream iss(line);
if (iss >> date >> amount)
{
cout << date << "\t\t$" << showpoint << fixed << setprecision(2) << amount << endl;
famount += amount;
}
}
cout << "Your balance is $" << famount << endl;
cout << "How much would you like to deposit today: $";
cin >> amountinput;
float newbal = 0;
newbal = (famount += amountinput);
cout << "\nYour new balance is: $" << newbal << ".\n";
file << date << "\t\t" << newbal; //***This should be writing to file
but it doesn 't.
file.close();
The text file looks like this:
Tony Gaddis
05/24/12 100
05/30/12 300
07/01/12 -300
// Console Output looks like this
Tony Gaddis
05/24/12 100
05/30/12 300
07/01/12 -300
Your balance is: #1
How much wuld you like to deposit: #2
Your new balance is: #1 + #2
write to file
close file.
// exits to main loop::::
How can I make it write to file and save it, and why is this happening.
I tried doing it with ostringstream as well considering how I used istringstream for the input. But it didn't work either:
float newbal=0;
newbal = (famount += amountinput);
ostringstream oss(newbal);
oss << date << "\t\t" << newbal;
I am trying to self teach C++ so any relevant information would be kindly appreciated.
If you want to write a text file, you should not use "ios::binary", when opening the file.