I'm done with my assignment for a beginner C++ course, and the only annoying thing is I cannot get rid of the extra space that appears on the screen when I input data from a file and print to screen while outputting to another file.
I have looked into the input.ignore() and putback() functions, but I cannot get them to work while messing around.
I know this is cause the extra \n character is at the end of the first line, or cause I skipped the comma.
Any tips would be great, in terms of formatting a .ignore() or .putback(), as the professor rushed through explaining it at the end of class as we were leaving without examples.
It outputs to the screen as such:
John 13333 .69 // one extra space after John for every number and item
Susie 12222 .75...
#include <iomanip> //include directives to use various keywords
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <limits>
using std::cin; //various usings to avoid namespace std
using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::string;
using std:: left;
using std::setw;
using std::numeric_limits;
void getName(string & fileName);
void readandsend(ifstream &input,ofstream &output);
int main()
{
//my variables I will use in function calling
string fileN;
ifstream input;
ofstream output;
getName(fileN); //calls to functions
input.open(fileN); //opens file to be streamed for input
output.open("Assgn6-BB.txt");
if (!input)
{
cout << "The input file failed to open! Try again." << endl; //checks that the file opened correctly
return -1;
}
cout << "============================================================" << endl; //prints header
cout << "=" << " ";
cout << "FARMER'S MARKET INVENTORY" <<" " << "=" <<endl;
cout << "============================================================" << endl;
readandsend(input, output);
return 0;
}
void getName(string & fileName)
{
//pre-conditions: a corrcet filename is entered by the user that exists and has data
//post-conditions: a filename is entered and processed without error to be used later
cout << "Enter the name of the file: "; //takes in file name
cin >> fileName;
}
void readandsend(ifstream &input,ofstream &output)
{
//pre-conditions: filename is a correct file that exists and has data that is opened correctly
//post-conditions: prints out the data from the file until the end of the file is reached while outputting the data and calculations to another file
char farm[25];
string item;
int numItems;
double pricePer, subTotal, total = 0, totalItems = 0;
input.getline(farm,25,','); //reads in first set of data to make sure the standard input.eof reads correctly
input >> numItems;
input >> item;
input >> pricePer;
totalItems += numItems;
total +=(pricePer * numItems);
while(!(input.eof()))
{
output << left << setw(25) << farm //sends to output file
<< setw(10) << numItems << setw(15)
<< item << setw(8) << pricePer
<< setw(8) << (numItems * pricePer);
cout << left << setw(25) << farm //prints to screen to verify
<< setw(10) << numItems
<< setw(15) << item
<< setw(8) << pricePer
<< setw(8) << (numItems*pricePer) << endl;
input.getline(farm, 25, ',');
input >> numItems;
input >> item;
input >> pricePer;
totalItems += numItems;
total += (pricePer * numItems);
}
cout << left << setw(24) << "Grand Total: " << totalItems << " items's totaling $" << total << endl;
input.close(); //closes the files
output.close();
}
Related
I am having issues with cin.getline(). When I put it into the below program, it is giving an error:
no instance of overload function (ect) matches the argument list
I am also having an issue with my variable nx. The compiler says that it cannot be a constant, but I'm not sure how it is.
Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//create a class for one book
class Book
{
//member variables
public:
string title;
string author;
int year;
//function to print the book details
void print()
{
cout << "Title: " << title << endl;
cout << "Authot: " << author << endl;
cout << "Year: " << year << endl;
}
};
int main()
{
std::string filename, temp;
//prompt the user to enter the file name
cout << "Enter filename: ";
cin >> filename;
//open the file
fstream file;
file.open(filename.c_str());
int nx;
//read the first line of the file to know the number of books
file >> nx;
//move to the next line of the file
std::cin.getline(file, temp);
//allocate an array of n Book
Book books[nx];
//read the data for n books from the file
for (int i = 0; i < nx; i++)
{
//read file and initialize the books array
std::cin.getline(file, books[i].title);
std::cin.getline(file, books[i].author);
file >> books[i].year;
//move to the next line of the file
getline(file, temp);
}
//Display the output
cout << "Books found: " << nx << endl;
for (int i = 0; i < nx; i++)
{
cout << "\nBook " << i + 1 << ":" << endl;
cout << "Title: " << books[i].title << endl;
cout << "Author: " << books[i].author << endl;
cout << "Year: " << books[i].year << endl;
}
}
The 2-parameter std::cin.getline() method does not take a std::fstream or a std::string as parameters. It takes a char* and a std::streamsize instead, as it is meant to fill a char[] buffer. To fill a std::string from a stream, you need to use the standalone std::getline() function instead, eg:
std::getline(file, temp);
...
std::getline(file, books[i].title);
...
As for the "constant" error relating to your nx variable, the problem is on this line:
Book books[nx];
You are trying to declare a fixed-sized array using a size that is not known until runtime. You can't do that in standard C++, an array's size must be known at compile-time instead. Otherwise, you have to use new[] or std::vector to allocate the array dynamically at runtime instead, eg:
Book* books = new Book[nx];
...
delete[] books;
Or:
#include <vector>
std::vector<Book> books(nx);
Demo
On a side note:
When you want to discard content from an istream up to the next '\n' character, you can use the stream's ignore() method instead of std::getline(), that way you are not wasting memory unnecessarily for an unused std::string, eg:
#include <limits>
//move to the next line of the file
//std::getline(file, temp);
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Also, you have defined a print() method in Book, but you are not actually using it. Your final display loop can do this instead:
//Display the output
cout << "Books found: " << nx << endl;
for (int i = 0; i < nx; i++)
{
cout << "\nBook " << i + 1 << ":" << endl;
/*
cout << "Title: " << books[i].title << endl;
cout << "Author: " << books[i].author << endl;
cout << "Year: " << books[i].year << endl;
*/
books[i].print();
}
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'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";
I am trying to search a specific ID/ registration from a .txt and display the corresponding info accordingly. In this case I want to display the pricing according to the corresponding registration number which should be entered.
Reading and writing files is not the issue for me. There is a lot of info on the web in regards with reading and writing, but not much on searching and displaying according to the ID/ registration.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
string line;
double cost;
string reg;
ifstream in_stream;
ofstream out_stream;
char registration[10];
//Open file
in_stream.open("Fines.dat");
//Error if opening fails
if (in_stream.fail())
{
cout << "Input file could not open. " << endl;
exit(1);
}
//Open out stream file
out_stream.open("OutStandingFines.dat");
//Error if opening fails
if (out_stream.fail())
{
cout << "Output file opening failed.\n";
exit(1);
}
//Display original .dat file
cout <<"Original .dat File" << endl;
if(in_stream.is_open())
{
while(in_stream >> reg >> cost)
{
cout << reg <<" " << cost << '\n';
}
in_stream.close();
}
else
{
cout <<"File is not open: " << endl;
}
/////////////My problem is from here//////////////////////////
//Enter the registration number you wish to search
cout << "Please enter registration number: " << endl;
cin >>registration;
//I must display all cost values that have the same registration number???????? I need help with this
/*
for (int i = 0; i < 10; i++)
{
if( reg == registration)
{
cout << fixed << setw(2)<< setprecision(2) <<"R " << cost << '\n';
out_stream << fixed << setw(2)<< setprecision(2) << "R "<< cost << endl; //send back to .dat
}
}
*/
in_stream.close();
out_stream.close();
system("pause");
return(0);
}
Ok, I managed to get the output. The problem I have now is to display all the values with the same registration/ ID.
For some reason only the last row in the fstream .txt gets displayed when I enter "ABC123".
The input .txt contains the following info.
ABC123 400
DEC234 340
ABC123 500
GED345 600
ABC123 240
GEE600 120
GED345 230
GEE600 470
ABC123 120
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
string line;
double cost;
string reg;
ifstream in_stream;
ofstream out_stream;
string registration;
in_stream.open("Fines.dat");
if (in_stream.fail())
{
cout << "Input file could not open. " << endl;
exit(1);
}
out_stream.open("OutStandingFines.dat");
if (out_stream.fail())
{
cout << "Output file opening failed.\n";
exit(1);
}
//Display original .dat file
cout <<"Original .dat File" << endl;
if(in_stream.is_open())
{
while(in_stream >> reg >> cost)
{
cout << reg <<" " << cost << '\n';
}
}
else
{
cout <<"File is not open: " << endl;
}
//Enter Registration here
cout << "Please enter registration number: " << endl;
cin >>registration;
//compare and display all registration numbers that match
cout <<"Fines: " << endl;
if(out_stream.is_open())
{
while(reg == registration)
{
cout << fixed << setw(2)<< setprecision(2) <<"R " << cost << '\n';
out_stream << fixed << setw(2)<< setprecision(2) << "R "<< cost << endl; //send back to .dat
exit(1);
}
}
else
{
cout <<"File is not open: " << endl;
}
in_stream.close();
out_stream.close();
system("pause");
return(0);
}
Down below is my incomplete program. I am having problems with writing to a text file. For example I want to write the number of snow days to a text file, but nothing shows up in the textfile when I debug in VS 2010. It does display my info and name, but nothing else works. It wont write anything after that. its NOT writing to a text file.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
const string INFORMATION = "College Class";
const string MY_NAME = "Tom Hangler";
int main(void)
{
ofstream outFile;
int numberOfSnowDays;
int greatestSnowDay;
int dayNumber;
double amounttOfSnow;
outFile.open("Ex1Out.txt");
outFile << setw(51) << INFORMATION << endl << setw(48) << MY_NAME << endl;
cout << "Please enter num of days it snowed: " << endl;
cin >> numberOfSnowDays;
outFile << setw(10) << "Number of days of snow is: " << setw(10) << numberOfSnowDays;
int index;
//Problem 1 for-loop
for (index = 0; index < numberOfSnowDays; index++)
{
cout << "Enter day: " << endl;
cin >> dayNumber;
cout << "Enter amount of snow: " << endl;
cin >> amountOfSnow;
};
return 0;
}
here is what my output displays:
College Class (centered)
Tom Hangler (centered)
If i try to write anything after this, Nothing is written ever to the output file. And the output text file IS in my VS project that contains my .cpp file. I added the text file to project.
Try closing the stream at the end of the function, it looks like the data isn't getting flushed.
outFile.close();
Your code compiles and works on gcc 4.4.5 (apart from typo in amounttOfSnow).
Is it possible that you are looking at an old Ex1Out.txt file ?
Its most likely created in the Release or Debug subdirectory in your project, not where the .cpp files are.
in your for loop, you only collect the amount of snow, but you don't write it to the text file.
Do you want to do something like this?
...
for (index = 0; index < numberOfSnowDays; index++)
{
cout << "Enter day: " << endl;
cin >> dayNumber;
cout << "Enter amount of snow: " << endl;
cin >> amountOfSnow;
// next line is new:
outFile << "Day#: "<< dayNumber << ", snow: "<< amountOfSnow<<endl;
};
outFile.close()
...