Can't get outfile to read data from infile(c++) - c++

Data in the input file:
Wilson Jack 87236.45 11
My code:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ofstream out;
ifstream in;
string Lastname, Firstname;
double salary;
int increase;
in.open("Lab5_Ex_3_Input.txt");
out.open("Lab5_Ex_3_Output.txt");
in >> Lastname >> Firstname >> salary >> increase;
out << "Lastname: "<< Lastname << "Firstname " << Firstname << "salry :" << salary <<"increase: "<< increase <<endl;
in.close();
out.close();
return 0;
}
So, when I check the output file I am getting:
Lastname: Firstname salry :-9.25596e+061increase: -858993460
what am I doing incorrectly?

Try this:
if (!(cin >> value >> value2 >> value3)) {
cout << "input failed" << endl;
return -1;
}
My guess is that your input fails. You could also check if the file was opened correctly at all, which your code is missing.
BTW: There's no need to explicitly close the streams, they are closed automatically when they go out of scope and their destructor is called.

Your program is likely having trouble reading the input file. Why? Based on the output values:
Lastname: Firstname salry :-9.25596e+061increase: -858993460
This is due to the fact that both Lastname and Firstname are empty (i.e. there is nothing after the colon), that the numbers following salry and increase is common when you've uninitialized your variables as you've done in your code.
What you should do is check to see if the file is open:
if (!in.is_open()) {
std::cerr << "Error opening input file!\n";
exit(1);
}

Related

C++ Reading a txt file containing multiple kinds of variables

My skills are very basic. I'm trying to make save and load functions for a text game. This is my code:
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
#include <sstream>
#include "variables.h"
// CORE FUNCTIONS
void save_game()
{
std::ofstream file((savefile_path + "/" + player_name + ".txt").c_str());
if (file.is_open())
{
file << engine_switch << std::endl; //int
file << map_switch << std::endl; // int
file << sub_map_switch << std::endl; // int
file << player_name << std::endl; //string
file << player_class << std::endl; // string
//file << << endl;
file.close();
}
else
{
std::cout << "A PROBLEM OCCURED";
system("pause");
}
return;
}
void load_game()
{
system("cls");
std::cout << "ENTER THE SAVE FILE NAME (SAME AS YOUR CHARACTER NAME)\nOR PRESS ENTER TO GO BACK TO MAIN MENU: ";
fflush(stdin);
getline(std::cin, player_name);
std::string name=player_name;
std::ifstream file((savefile_path + "/" + player_name + ".txt").c_str());
if(file)
{
file >> engine_switch; // this is int
file >> map_switch; // this is int
file >> sub_map_switch; /this is int
file >> player_name; //string
file >> player_class; //string
//file >> ;
return;
}
else
{
if(player_name=="\0")
{
engine_switch=1;
return;
}
else
{
system("cls");
std::cout << "COULDN'T OPEN THE SAVE FILE" << std::endl;
system("pause");
load_game();
}
}
engine_switch=1;
return;
}
The problem happens when I enter a player_name compound of multiple words separated with a space. For example when I enter "name name" the player_name becomes name and the player_class becomes name and the actual player_class is not put into any variable.
I tried the rdbuf() function, but didn't work and I don't even understand it yet. I tried it with stream, string, c.str(), everything I found on the web and could comprehend, but it always comes out wrong.
When you extract a string from a stream, spaces are considered as separators.
It's even worse: in your code, the player_name is followed by player_class which is also a string. How should your program interpret this :
10 15 20 John William Doe hero B
How would your program guess that John William Doe is a composed name and hero B the category ?
The simplest solution is to write all your strings on a separate line in the file. When you load it you can then read it with getline():
file >> engine_switch; // this is int
file >> map_switch; // this is int
file >> sub_map_switch; /this is int
getline (file, player_name); //string
getline (file, player_class; //string
You need to use getline instead of the >> operator in your load-game function.
Instead of doing file >> player_name do getline(file, player_name)
This should be used in replacement of every occurrence of file >> someVar
EDIT: I didn't realize the others were integer values. For those you should still be using the >> operator.

Homework Assignment infile / outfiles

My assignment states the following :
Three employees in a company are up for a special pay increase. You are given a file, Ch3_Ex7Data.txt, with the following data:
Miller Andrew 65789.87 5
Green Sheila 75892.56 6
Sethi Amit 74900.50 6.1
Each input line consists of an employee's last name, first name, current salary, and percent pay increase.
For example, in the first input line, the last name of the employee is Miller, the first name is Andrew, the current salary is 65789.87, and the pay increase is 5 %.
Write a program that reads data from the specified file and stores the output in the file Ch3_Ex7Output.dat. For each employee, the data must be output in the following form: firstName lastName updatedSalary Format the output of decimal numbers to two decimal places.
My code is the following.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
//Declaring the variables
string firstName;
string lastName;
double payIncrease;
double pay;
ifstream inFile;
ofstream outFile;
inFile.open("C:\\Users\\Megan\\Ch3_Ex7Data.txt"); //opens the input file
outFile.open("C:\\Users\\Megan\\Ch3_Ex7Output.dat"); //opens a output file
outFile << fixed << showpoint;
outFile << setprecision(2); // Output file only having two decimal places
cout << "Processing Data....." endl; //program message
while (!inFile.eof() //loop
inFile >> lastName >> firstName >> pay >> payIncrease;
pay = pay*(pay*payIncrease);
outFile << firstName << " " << lastName << " " << pay << "/n";
inFile.close();
outFile.close();
return 0;
}
For some reason I cannot seem to get the code to open my existing .txt file, read it and then translate it to another file. Does anybody see anything wrong with this that could help me out?
You have many problems with you code.
The two most evident prevent the program from compiling:
cout << "Processing Data....." endl; //program message
should be:
cout << "Processing Data....." << endl; //program message
and while (!inFile.eof() //loop should be at least while (!inFile.eof() )//loop
That's not all:
while (!inFile.eof()) is an anti-idiom: you test for end of file, then read and do the processing even if an error or end of file has occured. You must test after reading.
And as you were said in comment, without { } only the first line after the while is repeated, which is not what you want.
The correct formula to add a percent increase is pay = pay*(1 + payIncrease/100.); at least pay = pay+(pay*payIncrease/100.);
Adding a '/n' as an end of line is plain wrong. The character is '\n' (note the backslash), and anyway you should always write endl in C++.
Once all that is fixed, the loop becomes:
for (;;) { //loop
inFile >> lastName >> firstName >> pay >> payIncrease;
if (! inFile) break; // exit on eof or error
pay = pay*(1 + payIncrease/100.);
outFile << firstName << " " << lastName << " " << pay << endl;
}
and the output is:
Andrew Miller 69079.36
Sheila Green 80446.11
Amit Sethi 79469.43
But is you want to learn good pratices, you should also:
test the opening of both files
test after end of loop if the termination was caused by an error and issue a warning
last by not least learn to use a debugger...
This was my solution
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
// Write your main here
//Declarations
string FirstName;
string LastName;
double Pay;
double Increase;
double UpdatedSalery;
//File object and open txt and dat files per instructions and use user input for the txt input file
ifstream FileIn;
string FileName;
cout << "enter a file name: ";
cin >> FileName;
FileIn.open(FileName);
ofstream FileOut("Ch3_Ex5Output.dat");
FileOut << setprecision(8);
while(FileIn >> LastName >> FirstName >> Pay >> Increase){
UpdatedSalery = ((Pay*(Increase/100))+Pay);
FileOut << " " << FirstName << " " << LastName << " " << UpdatedSalery << endl;
}
FileIn.close();
FileOut.close();
return 0;
}

FileObject reads input that is not in file, c++

I'm working on this program that is supposed to read data from a file that is formatted like the following, Code#Salary. The user is supposed to give a code, the program should find that code in the file if it exists and then return the salary. However, when I run the program, I keep getting a salary that is not even one of the options.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int code;
double salary;
int name;
ifstream inFile;
inFile.open("/Users/rsoni613/Desktop/payroll.txt");
if (inFile)
{
cout << "Enter payroll code: ";
cin >> code;
do
{
inFile >> name;
}
while (code != name);
inFile.ignore('#');
inFile >> salary;
inFile.close();
cout << "Salary: $" << salary << endl;
}
else
{
cout << "File did not open, please retry.";
}
return 0;
}
Here are the contents of input file, payroll.txt
1#23400
4#17000
5#21000
6#12600
9#26700
10#18900
11#18500
13#12000
15#49000
16#56500
20#65000
21#65500
22#78200
23#71000
24#71100
25#72000
30#83000
31#84000
32#90000
double salary;
variable salary is of type double. No wonder you are getting different result.

How do I pull information from one file and split the information to four other files?

I am trying to pull information from a single file, and using one piece of information (in this reference it will be someones major) I want to direct the information to four other files (according to the major). Sorry if this may be obvious to you, but I really suck at this. Here is what I have so far:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
double studNum;
float GPA;
string nameL;
string nameF;
char initM;
char majorCode;
ifstream inCisDegree;
ofstream outAppmajor;
ofstream outNetmajor;
ofstream outProgmajor;
ofstream outWebmajor;
inCisDegree.open("cisdegree.txt");
if (inCisDegree.fail())
{
cout << "Error opening input file.\n";
exit(1);
}
outAppmajor.open("appmajors.txt");
outNetmajor.open("netmajors.txt");
outProgmajor.open("progmajors.txt");
outWebmajor.open("webmajors.txt");
while (inCisDegree >> studNum >> GPA >> nameL >> nameF >> initM >> GPA >> majorCode);
inCisDegree >> studNum >> nameL >> nameF >> initM >> GPA >> majorCode;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
This is basically as far as I got. I had a little more, but it was only to show me if it worked or not. It seems the studNum (student number in the file) did manage to work, however, everything else does not seem to work properly. I am also having issues in figuring out how to properly put the information into one of the four files. Thanks for any help. I have been trying for hours to get this to work, but my mind has been pulling blanks.
edit: The information in the input file looks like: 10168822 Thompson Martha W 3.15 A
which translates to: studNum, nameL, nameF, initM, GPA, majorCode
Looking at the line
while(inCisDegree >> studNum >> GPA >> nameL >> nameF >> initM >> GPA >> majorCode);
because you have a semicolon at the end, this won't be a loop (presuming it's just this way for testing but thought i'd mention it anyway).
However the main problem with this line is that you've specified your text file to be of the format
studNum, nameL, nameF, initM, GPA, majorCode
where here you are trying to read in
studNum, GPA, nameL, nameF, initM, GPA, majorCode
apart from reading a value twice, the first read in for GPA is trying to read a string into a float, and this is probably throwing an exception somewhere inside <iostream> (i don't know exactly what the behaviour is but it won't work). this is breaking your read and the rest of the variables won't read in from the file.
this code should do what you're trying to accomplish.
I've changed studNum from a double to a long as you don't seem to have any reason for it to use double, and in all likelyhood you could probably use unsigned int as an 8 digit number won't overflow 2^32 anyway.
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
long studNum;
float GPA;
string nameL;
string nameF;
char initM;
char majorCode;
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
ifstream inCisDegree;
ofstream outAppmajor;
ofstream outNetmajor;
ofstream outProgmajor;
ofstream outWebmajor;
inCisDegree.open("cisdegree.txt");
if (inCisDegree.fail()) {
cout << "Error opening input file.\n";
exit(1);
}
outAppmajor.open("appmajors.txt");
outNetmajor.open("netmajors.txt");
outProgmajor.open("progmajors.txt");
outWebmajor.open("webmajors.txt");
while (inCisDegree.good()) {
string line;
getline(inCisDegree, line);
istringstream sLine(line);
sLine >> studNum >> nameL >> nameF >> initM >> GPA >> majorCode;
cout << studNum << " " << nameL << " " << nameF << " " << initM << " " << GPA << " " << majorCode << endl;
// this line is just so we can see what we've read in to the variables
}
}

C++ Displaying a Text File...("Echo" a Text File)

So I'm really stuck trying to figured this bug on the program that is preventing me from displaying the text of my program..
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
#include <stdio.h>
using namespace std;
int main ()
{
ifstream infile;
ofstream offile;
char text[1024];
cout <<"Please enter the name of the file: \n";
cin >> text;
infile.open(text);
string scores; // this lines...
getline(infile, scores, '\0'); // is what I'm using...
cout << scores << endl; // to display the file...
string name1;
int name2;
string name3;
int name4;
infile >> name1;
infile >> name2;
infile >> name3;
infile >> name4;
cout << "these two individual with their age add are" << name2 + name4 <<endl;
// 23 + 27
//the result I get is a bunch of numbers...
return 0;
}
Is there any way cleaner or simple method i can used to display the file ?
All the method in the internet are difficult to understand or keep track due to
the file is open in loop..
I want a program that you type the name of the file and displays the file
the file will contain the following...
jack 23
smith 27
Also I need to obtain data from the file now I'm using the above code to obtain that information from the file...
loop is probably the best thing you can do.
so if you know the format you could simply do it like this
#include <iostream>
#include <fstream>
using namespace std;
int printParsedFile(string fileName) { // declaration of a function that reads from file passed as argument
fstream f; // file stream
f.open(fileName.c_str(), ios_base::in); // open file for reading
if (f.good()) { // check if the file can be read
string tmp; // temp variable we will use for getting chunked data
while(!f.eof()) { // read data until the end of file is reached
f >> tmp; // get first chunk of data
cout << tmp << "\t"; // and print it to the console
f >> tmp; // get another chunk
cout << tmp << endl; // and print it as well
} else {
return -1; // failed to open the file
}
return 0; // file opened and read successfully
}
you can call then this function for example in your main() function to read and display file passed as argument
int main(int argc, char** argv) {
string file;
cout << "enter name of the file to read from: "
cin >> file;
printParsedFile(file);
return 0;
}
I personally use stringstreams for reading one line at a time and parsing it:
For example:
#include <fstream>
#include <stringstream>
#include <string>
std::string filename;
// Get name of your file
std::cout << "Enter the name of your file ";
std::cin >> filename;
// Open it
std::ifstream infs( filename );
std::string line;
getline( infs, line );
while( infs.good() ) {
std::istringstream lineStream( line );
std::string name;
int age;
lineStream >> name >> age;
std::cout << "Name = " << name << " age = " << age << std::endl;
getline( infs, line );
}