outFile C++ not writing to output text - c++

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

Related

Extra Space in first line of input from a file C++

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

Xcode won't recognize/read file properly

I built a program in c++ to calculate the amount of gas money I owe to my dad for my summer job at Domino's. What the program does is read two lines from a file in a do while loop, one for the starting mileage that day and one for the ending mileage of that day. However I just can't get the program to read the file properly. I'm positive I opened it correctly and put it in the right spot (same folder as the .cpp file) but it just won't read it properly. Any ideas?
#include <iomanip>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile;
inputFile.open("sample.txt");
int days; // number of days Alisha worked
int count = 1;
int totalMileage = 0;
int addMileage;
int startMileage;
int endMileage;
double avgMileage;
double moneyOwed;
double realOwed;
const double PER_MILE = 0.08125;
cout << endl;
cout << "How many days did Alisha work?" << endl;
cin >> days;
days++;
do
{
inputFile >> startMileage;
cout << "The starting mileage for day " << count << " is " << startMileage << endl;
inputFile >> endMileage;
cout << "The ending mileage for day " << count << " is " << endMileage << endl;
addMileage = endMileage - startMileage;
totalMileage = totalMileage + addMileage;
count++;
cout << endl;
}
while (count != days);

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

Reading a text file and saving every line as a string (C++)

I have a little question. I'm currently doing a school assignment in c++ and the task is to have something similar to a small library, where the user can ask to look at a book and then the program will print out the release year, author, how many pages etc etc. The assignment is focused on vectors and arrays, but I thought a smart way of doing it could be to have the release years in a text file and then save those years in an array. When I first it, everything was saved in characters, (meaning "1","8","8","5"), when I'd actually like it to save every line in the text document as a string in the array, or something similar (like this: "1885",). I couldn't really figure out how to split them up into strings then. I then talked a bit to a friend and this is where I am with my code now, it's not really working and at the moment I have no idea how I am supposed to solve it. Main problem is I don't know how to read and save every line in the text document as a string, however I am grateful for any help that would make me be able to print out a single year from the text document, in any other way.
This is what my code looks like:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <vector>
#include <istream>
using namespace std;
void book();
void readFile(int input);
void oddEven();
void stringLiner();
void factorial();
int main()
{
int input;
while (input != 0)
{
cout << "Hello. Welcome to the first, truly big, assignment in this programming course." << endl;
cout << "Which part do you wish to access?" << endl;
cout << "1. Book program" << endl;
cout << "2. 2 arrays - One EVEN ~ One ODD" << endl;
cout << "3. The one at a time string" << endl;
cout << "4. Factorial array" << endl;
cout << "0. Exit " << endl;
cin >> input;
switch (input)
{
case 1:
book();
break;
}
}
}
void book() //This is the function used to do the book thing
{
cout << string( 100, '\n' );
int input;
string year[5] = {"1883"/*Treasure Island*/ }; //Array for the years the books were written
string author[5] = {"Robert Louis Stevenson"/*Treasure Island*/, "yollo"}; //Array for the authors
string pages[5] = {"304"/*Treasure Island*/,"420" }; //Array for the number of pages
string books[5] = {"Treasure Island", "Swagolo" }; //Array for the name of the books
cout << "You have chosen to look at books." << endl;
cout << "These are the books in the library. Pick one to see what year it was written in, what author wrote it and how many pages it contains. " << endl;
cout << "These are the books in the library: " << endl;
for (int i = 0; i<5; i++) //Loop to display all the books + what number to press to access them.
{
cout << i+1 << " " << books[i] << endl;
};
cout << "Please type a number to look at that book. " << endl;
cin >> input;
int TresIsl = input-1;
switch (input) //Switch case to chose which book to look at.
{
case 1: //Info about Treasure Island
cout << "This is " << books[TresIsl] << " and this is some info. " << endl << endl;
cout << books[TresIsl] << " was released in " ;
readFile(input);
cout << " and it was written by " << author[TresIsl] << ". ";
cout << "This book contains " << pages[TresIsl] << " pages. " << endl;
break;
case 2:
cout << "This is " << books[TresIsl] << " and this is some info. " << endl << endl;
cout << books[TresIsl] << " was released in " ;
readFile(input);
cout << " and it was written by " << author[TresIsl] << ". ";
cout << "This book contains " << pages[TresIsl] << " pages. " << endl;
break;
}
}
void readFile(int input)
{
ifstream file("year.txt");
int numlines = 0;
int numMaxLines = 5;
vector<string> lines (numMaxLines);
while(numlines < numMaxLines && !file.eof())
{
getline(file, lines);
numlines++;
}
cout << lines[input];
}
The other void functions are for other tasks in this assignment which I didn't include now, I just copy pasted the code where they were included. Also please don't mind the slightly childish stuff in the code.
Also I am very sorry if this breaks any rules for the forum or something similar. I tried to find another topic like this for c++, but I couldn't find anything helpful.
It's not clear what exactly your problem is, but assuming that you want to read a file line-by-line and get a vector of those lines, something like this would do it:
std::vector<std::string> readLines(const std::string& filename)
{
std::vector<std::string> lines;
std::ifstream input(filename);
std::string line;
while (std::getline(input, line))
{
lines.push_back(line);
}
return lines;
}
if any one's still got a question, a friend and me discussed it and he helped me a bit, and we got a code that works in my case at least, so I thought I'd show it to you:
void readFile(int input)
{
ifstream file("year.txt");
string in;
vector<string> lines;
if (file.is_open())
{
while ( getline (file, in) )
{
lines.push_back(in);
}
cout << in;
}
file.close();
cout<<lines[input-1]<<endl;
}
The cout in the end I guess is unnecessary in some cases, but this worked for me and my homework. Thanks for everyone's help anyways.

How Read from a Data File into a Structure of Vectors

I am trying to figure out how to store binary data that is saved to a .dat file "customer.dat" into a structure of vectors. I thought I have had it a few times, but with no luck.
Basically, I have a working method of storing the data into the .dat file, the newEntry function, but I can not seem to work out on how to bring the data back one set at a time into an order structure of vectors. The function in question is the searchDisplay function. Here is the code:
#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;
const int NAME_SIZE = 51, ADDR_SIZE = 51, PHONE_SIZE = 14;
struct Client {
char name[NAME_SIZE];
char address1[ADDR_SIZE];
char address2[ADDR_SIZE];
char phone[PHONE_SIZE];
double acctBal;
double lastPay;
};
//void welcome();
int menu();
int newEntry();
int searchDisplay();
int main() {
int selection;
int option = 0;
int end;
//welcome();
while (option != 6) {
selection = menu();
if (selection == 1) {
cin.ignore();
end = newEntry();
if (end == 0) {
return 0;
}
} else if (selection == 2) {
end = searchDisplay();
if (end == 0) {
return 0;
}
}
}
return 0;
}
int menu() {
int selection;
cout << "User please enter the number that corresponds with what you wish to do..."
<< endl;
cout << "1) Add An Entry" << endl
<< "2) Search for a Specfic Person and erase." << endl;
cin >> selection;
return selection;
}
int newEntry() {
string input;
Client person;
char response = 'y';
//create file object and open file
fstream customer("customer.dat", ios::app | ios::binary);
if (!customer) {
cout << "Error opening file. Program aborting." << endl;
return 0;
}
do {
cout << "Enter person information:" << endl << endl;
cout << "Name: " << endl;
getline(cin, input);
strcpy(person.name, input.c_str());
cout << endl << person.name;
cout << endl << "Street Adress (And Apartment Number):" << endl;
cin >> person.address1;
getline(cin, input);
strcpy(person.address1, input.c_str());
cout << endl << "City, State, Zipcode: " << endl;
cin >> person.address2;
getline(cin, input);
strcpy(person.address2, input.c_str());
cout << endl << "Phone: " << endl;
cin >> person.phone;
getline(cin, input);
strcpy(person.phone, input.c_str());
cout << endl << "Account Balance: " << endl;
cin >> person.acctBal;
//input validation to ensure a non neg number
cin.ignore();
cout << endl << "Last Payment: " << endl;
cin >> person.lastPay;
//input validation to ensure a non neg number
customer.write(reinterpret_cast<char *>(&person), sizeof(person));
cout << endl << "Do you want to enter another record? (Enter Y for Yes, N for No) " << endl;
cin >> response;
cout << "_______________________________________________" << endl << endl;
if (toupper(response) == 'Y') {
cin.ignore();
}
} while (toupper(response) == 'Y');
customer.close();
return 1;
}
/********************************************
My main problem is with the below function
********************************************/
int searchDisplay() {
vector<Client> store(2);
Client foo;
int i = 0;
fstream customer("customer.dat", ios::in | ios::binary);
if (!customer) {
cout << "Error opening file. Program aborting." << endl;
return 0;
}
//MY HOPE WAS THIS WOULD STORE EACH SET OF DATA INTO THE STRUCTURE OF VECTORS
customer.read(reinterpret_cast<char *>(&store), sizeof (store[0]));
while (!customer.eof()){
cout << store[i].name << ":" << endl
<< store[i].address1 << endl
<< store[i].address2 << endl
<< store[i].phone << endl
<< store[i].acctBal << endl
<< store[i].lastPay << endl << endl;
i++;
customer.read(reinterpret_cast<char *>(&store), sizeof (store[i]));
}
customer.close();
return 1;
}
Sorry if any of the coding is a little off in its indenting, I was having issues with the method of putting the code onto the text block.
But yes, any help would be great. This is my first time working with vectors significantly and first time ever with more file classes.
Your first problem is the opening of the data file for writing. You are currently opening it with the flag "ios::app", when it should be "ios::out". Over here (gcc version 4.7.2) i get no output to file when opening the file with "ios::app".
Using "ios::out" it creates a file and dumps the data into it.
The second problem is in the line where you open and read the file. You are missing a "[0]". Check the corrected version below:
customer.read(reinterpret_cast<char *>(&store[0]), sizeof (store[0]));
Making this modifications you can get closer to the desired results.
The main problem here is that writing and reading binary files is a bit different from regular text files, that have indications of line endings, for example. You need to organize your data differently, which can be quite complicated. Try Serializing with Boost.