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.
Related
So, I am trying to implement a function that can read a file and save some variables to it. The text file will look like this
- Account Number: 12345678
- Current Balance: $875.00
- Game Played: 2
- Total Amount Won: $125.00
- Total Amount Loss: $250.00
So far, I am able to read the account number but when I try to read the rest using the same method, nothing gets outputted to the console.
Here is my progress so far.
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inFile;
int accNum;
string accID;
int games;
double balance;
double amountWon, amountLost;
// Check if file with account number exists
cout << "Please enter account number: ";
cin >> accNum;
// Append correct format to string
accID.append("acc_");
accID.append(to_string(accNum));
accID.append(".txt");
// Open the file
inFile.open(accID);
// Check if the account number exists
if (!inFile)
{
cout << "Account number does not exist.\n";
}
int num;
string str, str2, str3;
// Read through the file
while (inFile >> str >> str2 >> str3 >> num)
{
cout << num << " ";
}
return 0;
}
When I run this code, I can get the account number to be output, but when I try adding more variables to read through the rest of the file nothing gets output to console.
You can use std::getline to read the rest of the file as shown below:
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
int accNum;
string accID;
int games;
double balance;
double amountWon, amountLost;
// Check if file with account number exists
cout << "Please enter account number: ";
cin >> accNum;
// Append correct format to string
accID.append("acc_");
accID.append(to_string(accNum));
accID.append(".txt");
std::cout<<accID<<std::endl;
// Open the file
ifstream inFile(accID);
if(inFile)
{
std::string strDash,strTitle, strNumber;
int num;
// Read through the file
while (std::getline(inFile, strDash, ' '),//read the symbol -
std::getline(inFile, strTitle, ':'), //read the title(for eg, Account number,Current Balance etc)
std::getline(inFile, strNumber, '\n')) //read the number at the end as string
{
std::cout<<strDash<<" "<<strTitle<<strNumber<<std::endl;//print everything read
}
}
// Check if the account number exists
else
{
cout << "Account number does not exist.\n";
}
return 0;
}
The output of the program can be seen here.
I am working on a C++ compiler called Online GDB. I need to write a program that asks the user for a file name then reads from this data to calculate an average then displays the data.
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
// functions
string getFileInfo();
double calculateMean (string fileName);
// main
int main ()
{
string filename = getFileInfo(); // getting file name
double mean = calculateMean( filename); // avg
cout << "The mean was" << endl;
return 0;
}
// function for getting file
string getFileInfo() {
string filename;
ifstream inputFile; // varibles
// asking user for the name
cout << "Please enter a file name to read from: ";
cin >> filename;
inputFile.open(filename);
// opening name and checking if its good.
if (inputFile)
{
inputFile.close();
}
// if the file is not good
else
{
cout << "Error: Please enter a file name to read from: ";
cin >> filename;
}
return 0;
}
// funtion for mean
double calculateMean(string fileName)
{
ifstream infile;
float num=0;
float total = 0.0;
int count = 0;
infile.open(fileName);
// While infile successfully extracted numbers from the stream
while(infile >> num) {
total += num;
++count;
}
// don't need the file anymore, close it
infile.close();
// give the average
return total/count;
}
My part for finding the average is working but I am having trouble with the naming of the file.
It runs and it asks me for the name and when I enter it goes straight to the error and input again and then it displays this:
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct null not valid
Aborted.
I have never seen this before and I have tried creating a file and if I don't then nothing displays.
This code is fully working
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
//int calculatorMin(string fileName);
//void displayInfo(double mean, int main);
string getFileInfo();
double calculateMean (string fileName);
// main
int main ()
{
string filename = getFileInfo(); // getting file name
double mean = calculateMean( filename); // avg
return 0;
}
// function for getting file
string getFileInfo() {
string filename;
ifstream inputFile;
cout << "Please enter a file name to read from: ";
cin >> filename;
inputFile.open(filename);
if (inputFile)
{
inputFile.close();
}
else
{
cout << "Error: Please enter a file name to read from: ";
cin >> filename;
}
//if it opens then name is good and close file then return name
//if it didn't open, ask for a new name.
return filename;
}
// funtion for mean
double calculateMean(string fileName)
{
ifstream infile;
float num=0;
float total = 0.0;
int count = 0;
infile.open(fileName);
// While infile successfully extracted numbers from the stream
while(infile >> num) {
total += num;
++count;
}
// don't need the file anymore, close it
infile.close();
cout << "The mean was " << total/count << endl;
// give the average
return total/count;
}
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);
}
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
}
}
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 );
}