For some reason outfile is not outputting a txt file in Windows. It has worked fine on the Mac (the line that's commented out in the code below), but in Windows I can't get it to output. Any guidance would be greatly appreciated. Thanks!
#include <iostream>
#include <fstream>
using namespace std;
int iNumberOfEmployees(); // this function prompts the user for the number of employees.
int iMissedDays(int employees); // this function prompts the user for the number of days each employee missed and returns the total.
double dAverageMissedDays(int employees, double missedDays); // this function calculates the average missed days per employee.
int main() {
int iGetEmployees = iNumberOfEmployees();
int iGetMissedDays = iMissedDays(iGetEmployees);
cout << "Average missed days: "<< dAverageMissedDays(iGetEmployees,iGetMissedDays) << endl;
// outputs results to a text file
ofstream outfile;
// outfile.open ("/Users/chrisrukan/Documents/CS140/Project 3/output.txt");
outfile.open ("C:\CS140\Project 3\output.txt");
if (outfile.is_open()) {
outfile << "Average missed days: "<< dAverageMissedDays(iGetEmployees,iGetMissedDays);
outfile.close();
}
else {
cout << "Error opening file" << endl;
}
}
int iNumberOfEmployees () {
int iTotalEmployees = 0;
// loop checks that the user doesn't enter a negative number of employees
while (iTotalEmployees <= 0) {
cout << "Enter the number of employees: ";
cin >> iTotalEmployees;
}
return iTotalEmployees;
}
int iMissedDays (int iEmployees) {
int iTotalMissedDays = 0;
int iIndividualMissedDays;
// loop asks the user the missed days for each individual employee
for (int i = 1; i <= iEmployees; i++) {
iIndividualMissedDays = -1;
// loop checks that user doesn't enter a negative number
while (iIndividualMissedDays < 0) {
cout << "Enter employee " << i << "'s number of missed days: ";
cin >> iIndividualMissedDays;
}
iTotalMissedDays += iIndividualMissedDays;
}
return iTotalMissedDays;
}
double dAverageMissedDays (int iEmployees, double dMissedDays) {
return dMissedDays / iEmployees;
}
In windows, file path are separated by \, you also need an extra \ if you need to pass file path as parameter to a function.
EDIT: according to #Benjamin Lindley, forward slashes will work on Windows too provided that the path is right.
There is also no root directory / as in Linux.
outfile.open ("/Users/chrisrukan/Documents/CS140/Project 3/output.txt");
Try to replace the string "/Users/chrisrukan/Documents/CS140/Project 3/output.txt" with windows file path format, absolute path starting from Disk name. e.g.,
"C:\\Users\\chrisrukan\\Documents\\CS140\\Project 3\\output.txt".
Or
`"C:/Users/chrisrukan/Documents/CS140/Project 3/output.txt"`
make sure those directories do exist.
A backslash in C++ is actually language syntax, for example \n means: new line, \t means: tab, in order to actually have a "\" in a string (as it stands right now you have a \C, \P, and \o which by the way all are considered one character each) you must type two \'s, for example
#include <iostream>
int main() {
std::cout << "\\";
}
outputs:
\
Also just a tip, files will automatically (by default if no other path is specified) be outputted/written to wherever the executable is stored.
Related
The only part of my code that has issue is the part that compares a string that has up to 2000 lines of data with a string that has 1 piece of data (input from the user). I added the else statement to show that the if statement is never true. My teacher was unable to figure out why it would evaluate to false. Can anyone tell me why that statement is always false, and how to fix it?
//
// main.cpp
// Assignment 5
//
//
#include <iostream>
#include <string>
#include <stdlib.h>
#include <iomanip>
#include <fstream>//for fin and fout
#include <string>
using namespace std;
int main()
{
//declare input and output file stream
ifstream fin;//in_s, inStream, input...
string name[2000], inName;//name is the string for the file, inName is the users name
string number[2000];
char again;
cout << "Welcome to the automated phone directory! " << endl << endl;
//Open the file streams and associate with the actual files
fin.open("/Users/ryoncook/Documents/School/Comp Sci/Assignments/Assignment 5/Asn Five_M/phoneNames.txt");
if (fin.fail())
{
cout << "Input file opening failed" << endl;
exit(1);//indicates 1 error occured
}
for(int i=0; i < 2000; i++)//loops until desired maximum size
{
getline(fin,name[i]);//stores the values of the file in the string array
}
fin.close();
//open number file
fin.open("/Users/ryoncook/Documents/School/Comp Sci/Assignments/Assignment 5/Asn Five_M/phoneNums.txt");
if (fin.fail())
{
cout << "Input file opening failed" << endl;
exit(1);//indicates 1 error occured
}
for(int i=0; i < 2000; i++)//loops until desired maximum size
{
getline(fin,number[i]);//stores the values of the file in the string array
}
//Close all open files
fin.close();
do{
cout << "Enter the name of the person you wish to look up: " << endl;
inName.clear();
getline(cin,inName);//reads the name desired as a string
for (int i=0; i < 2000; i++)
{
if (name[i] == inName)//compares input name with file name
{
cout << name[i] << "'s phone number is " << number[i] << endl;//prints result
}
else
{
cout << name[i] << inName;//i ran an else statement to confirm. The out if statement is never evaluated to be true
}
}
cout << "Would you like to find another phone number? (Y or N) " << endl;
cin >> again;
}while (again=='y' || again=='Y');
return 0;
}
//array for phone numbers and array for names that are both strings
//compare the 2 arrays and if they are equal, print
The for loop should find the name that the user entered, and if its in the file, it should select the correct name and phone number.
What actually happens is that even if the name entered is in the file, the statement is never true.
I know that the if statement is the issue because I printed out a few of the name and number strings with different numbers (number[12], name[6], etc.) and they all printed the correct name/number.
I am a newbie to C++ and I've got my first assignment. We've got a text file that contains 5 employee names, wages, and hours worked.
And this is my code so that my program could read it.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
int main()
{
ifstream input;
ofstream output;
string name;
int h;
float w;
int numEployee = 0;
double maxPay, minPay, avgPay;
int gross, adjGross;
//input/output file document path
input.open("/Users/jmduller/Documents/xcode/Lab1/Lab1/Employees.txt");
output.open("/Users/jmduller/Documents/xcode/Lab1/Lab1/Employeesoutput.txt");
//checks if the input file is working
if (input.fail())
{
cout << "Input file failed to open." << endl;
system("pause");
exit(0);
}
//checks if output file is working
if (output.fail())
{
cout << "Output file failed to open." << endl;
system("pause");
exit(0);
}
//prints the name, wage, hours worked of the employees to the output file
while (input >> name >> w >> h)
{
output << setw(5) << name << setw(5) << w << setw(5) << h << endl;
}
system("pause");
return 0;
}
It's reading it properly and giving me the output file that I want but there are missing items. The complete output file should be have the number of employees, max pay, min pay, avg pay, gross pay, and adjusted gross.
Can anyone help me point to the right direction?
Thanks
What you got to do is use some conditions and statements inside your while loop statement (which is reading from the file). Increment your 'numEmployee' variable everytime the loop executes(counts number of entries).
compare the 'w' read to check if it is lower than than the minPay(initialized to something very large) then update minPay otherwise if higher than maxPay(intialized to the least value possible) update maxPay.
Also, add the 'w' to another variable sumPay(initialized to zero) in loop and at the end divide it by numEmployee and you are done.
Just output them into the file before return statement.
Disclaimer: I am a beginner to programming, so what I say might sound really stupid
I have to make a "Telephone Directory" for school. The program isn't complete, but there are some things that I need to fix before moving on. The array TelephoneNumbers either isn't storing the numbers from the file correctly, or isn't displaying them. For the SeaerchRecords function, the first number in the file is displayed correctly, the second is displayed as "2147483647," and the rest of the numbers display as "0." The modify function also doesn't change the number, and I confirmed this with the while in the function. The string array works perfectly fine, however. May someone explain what I'm doing incorrectly?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string TelephoneNames[100];
int TelephoneNumbers[100];
void ModifyRecords(); //Function to Modify Records
void SearchRecords(); //Function to Search Records
void DeleteRecords(); //Function to Delete Records
int main()
{
fstream inputFile;
fstream outputFile;
char choice;
inputFile.open("Telephone Names.txt"); //To store
for (int count=0;count<100;count++) //file names
{ //into a
inputFile >> TelephoneNames[count]; //string
}
inputFile.close();
inputFile.open("Telephone Numbers.txt");//To store
for (int count=0;count<100;count++) //file #'s
{ //into a
inputFile >> TelephoneNumbers[count];//string
}
inputFile.close();
//Display options available
cout << " Hello, do you want to:\n";
cout << " ======================\n";
cout << "-Modify Records|Enter M\n";
cout << "-Search Records|Enter S\n";
cout << "-Delete Records|Enter D\n";
//Store choice
cin >> choice;
//Send to different function
if (choice=='M'||choice=='m')
{
ModifyRecords();
}
if (choice=='S'||choice=='s')
{
SearchRecords();
}
return 0;
}
void ModifyRecords()
{
string name;
string newname;
int newnumber;
int count=0;
cout << "Enter the name of the person: ";
cin >> name;
for (count=0;TelephoneNames[count]!=name;count++)//To determine where in the strings the new numbers need to be
{
}
cout << "Enter the new name of the person: ";
cin >> newname;
cout << "Enter the new number of the person: ";
cin >> newnumber;
TelephoneNames[count]={newname};
TelephoneNumbers[count]={newnumber};
count=0;
while (count<6)
{
cout << TelephoneNames[count] << endl;
cout << TelephoneNumbers[count] << endl;
cout << endl;
count++;
}
}
void SearchRecords()
{
string name;
int count=0;
cout << "Enter the name of the person you would like to find: ";
cin >> name;
for (count=0;TelephoneNames[count]!=name;count++)//To determine where in the strings the new numbers need to be
{
}
cout << "Name: " << TelephoneNames[count] << endl;
cout << "Number: " << TelephoneNumbers[count] << endl;
}
Since there is no any answer still and I don't see exactly the problem at this point I'll provide some suggestions how you can find a problem in your code.
In any programming situation when you can't find a bug, first task is to locate it as much precisely as you can and check all input data and assumptions. Usually, debugger is used for such purposes, but you can just output text in console before creating final version of your program.
To start with, you must check that you really received names and telephones from your file:
inputFile.open("Telephone Names.txt"); //To store
for (int count=0;count<100;count++) //file names
{ //into a
inputFile >> TelephoneNames[count]; //string
cout << TelephoneNames[count] << endl; //WE MUST SEE WHAT IS REALLY STORED IN TelephoneNames
}
inputFile.close();
inputFile.open("Telephone Numbers.txt");//To store
for (int count=0;count<100;count++) //file #'s
{ //into a
inputFile >> TelephoneNumbers[count];//string
cout << TelephoneNumbers[count] << endl; //WE MUST SEE WHAT IS REALLY STORED IN TelephoneNumbers
}
inputFile.close();
Ok, when it is checked and you are defenitely sure there is no problem in your data we can move to SeaerchRecords function doing the same procedure. We must check what is happening while you are searching:
for (count=0;TelephoneNames[count]!=name;count++)//To determine where in the strings the new numbers need to be
{
cout << "Search step: " << count << " name " << name << " found name " << TelephoneNames[count] << " number " << TelephoneNumbers[count] << endl;
}
Doing so you will locate your bug rather quickly. The problem can be in input files format, in difference of "name" and stored names format etc.
I'll provide several additional suggestion how you can improve your code.
1) Try to use const declarations for such commonly used things as number of records (const int NUMBER_OF_RECORDS = 100; insted of just putting '100' everywhere), it will reduce the amout of work and possible bugs. 2) Try to check all possible problems that you program can encounter if someting is wrong with data. What will happen if you have less than 100 records in your files now? Program crush or silent reading of unappropriate data which is even worse. Check that you haven't reach file end on any step of reading along with current check that you've reached you number of records and do something in case of unappropriate data.
3) Check the possible problems with conditions in your cycles not to run them infinite number of times. Now your condition for(count=0;TelephoneNames[count]!=name;count++)
will execute forever if there is no such name or just crush the program on count 100 or more. You should check that count doesn't exceed that value. Good luck!
I wrote a code which shows a question and 4 answers, ask to choose the correct one, and checks the choice.
Now I would build a table which would contain 6 columns: question/a/b/c/d/correct_answer, and about hundred of lines with my questions. Now I would like my program to randomly choose 5 of a question from table and show it to user.
First question is, can I do my table in Excel and use it than in Visual Studio? If not, what software should I use to do table like this as simply as possible, and how to implement it into my Visual studio project? If yes, how to implement Excel table to my Visual studio project?
Second question is, what simplest code should I write to randomly choose 5 of 100 question from my table?
A code of a question is:
int main()
{
string ans; //Users input
string cans; //Correct answer, comes from table
string quest; //Question, comes from table
string a; // Answers, come from table
string b;
string c;
string d;
int points; //Amount of points
points = 0;
cout << "\n" << quest << "\n" << a << "\n" << b << "\n" << c << "\n" << d << "\n";
cout << "Your answer is: ";
cin >> ans;
if (ans == cans)
{
points = points + 1;
cout << "Yes, it is correct\n";
}
else
{
cout << "No, correct answer is " << cans << "\n";
}
return 0;
}
First Part
You can definitely use Excel to edit your questions and save them. But when you save it, pay attention to the file format.
You want to save your Excel file as a .csv file instead of .xls or .xlsx file. Just go to File -> Save File As -> and change type to .csv.
This is because, reading .csv files is a lot easier. .csv files have each cell in row separated by a comma (,) and each row by a newline ('\n') character.
So, here is a sample Excel file:
After I save it as a .csv file and open it using a text editor (Atom, here), it looks like this:
After, that you only need to write some code to read the file.
This is the code I used (I've added excessive comments to make the code more explicit for beginners):
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;
const int MAX_QUESTIONS = 3;
const int COLUMNS = 6; //Question, Options A, B, C, D, Correct Answer
int main() {
ifstream fp;
fp.open("test.csv");
//If file could not be opened
if (fp.fail()) {
std::cout << "failed to open file" << std::endl;
return 1;
}
//Create a 2D vector of strings to store the values in the file
vector< vector<string> > table;
string line;
//Loop through the entire file (fp)
//Store all values found until I hit a newline character ('\n') in the string line
//This loop automatically exits when the end-of-file is encountered
while (getline(fp, line, '\n')) {
//Create an temporary vector of strings to simulate a row in the excel file
vector<string> row;
//Now I am passing in this string into a string stream to further parse it
stringstream ss;
ss << line;
string part;
//Similar to the outer loop, I am storing each value until I hit a comma into the string part
while (getline(ss, part, ',')) {
//Add this to the row
row.push_back(part);
}
//Add this row to the table
table.push_back(row);
}
//Print out the entire table to make sure your values are right
for (int i = 0; i <= MAX_QUESTIONS; ++i) {
for (int j = 0; j < COLUMNS; ++j) {
cout << table[i][j] << " ";
}
cout << endl;
}
return 0;
}
Second Part
To choose a random number, you can use this code (I borrowed it from another answer)
#include <random>
std::random_device rd; // only used once to initialise (seed) engine
std::mt19937 rng(rd()); // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(min,max); // guaranteed unbiased
auto random_integer = uni(rng);
Unlike the old method, this doesn't create bias towards the lower end. However, the new engine is available only in C++11 compilers. So keep that in mind. If you need to use the old method, you can correct the bias by following this answer.
To choose 5 different numbers, each time you generate a random number store it in an array and check whether this number has already been used. This can prevent repetition of questions.
To answer question 1: In Excel, click File>Save As. Choose UTF-16 Unicode Text (.txt), name your file, and save it where your program can access it. In your C++ program, use the fstream library for text files:
#include <fstream>
With the text file in the same directory, use
ifstream fin;
fin.open("FILENAME.txt");
.
.
.
fin >> variable;
.
.
.
fin.close();
To answer question 2: There is a rand() function that returns an integer between zero and RAND_MAX. Then you can use modulus(%) to get a random number in the desired range.
#include <cstdlib> // for srand() and rand()
#include <ctime> // for time()
.
.
.
srand(time(NULL)); // seed the RNG on seconds
.
.
.
var = rand() % ONE_MORE_THAN_MAX;
Here's a quizzer I made to help myself study:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include <ctime>
using namespace std;
const char QUESTIONS_FILE_NAME[] = "questions.dat";
const char QUESTION_ANSWER_SEPARATOR = ',';
const char QUESTION_SEPARATOR = '\n';
const short MAX_QUESTION_LENGTH = 300;
const short MAX_ANSWER_LENGTH = 300;
const short MAX_NUM_QUESTIONS = 300;
int main()
{
char questions[MAX_NUM_QUESTIONS][MAX_QUESTION_LENGTH];
char answers[MAX_NUM_QUESTIONS][MAX_ANSWER_LENGTH];
short counter = 0;
short question_choice;
char user_answer[MAX_ANSWER_LENGTH];
ifstream fin;
fin.open( QUESTIONS_FILE_NAME );
srand(time(NULL));
while(fin.getline( questions[counter], MAX_QUESTION_LENGTH-1,
QUESTION_ANSWER_SEPARATOR ))
{
fin.getline( answers[counter], MAX_ANSWER_LENGTH-1,
QUESTION_SEPARATOR );
counter++;
}
fin.close();
cout << endl << "Press CTRL+C to quit at any time" << endl << endl;
while ( counter > 0 )
{
question_choice = rand() % counter;
cout << endl << questions[question_choice] << " ";
cin >> user_answer;
if ( strcmp( user_answer, answers[question_choice] ) )
{
cout << endl << "Incorrect" << endl
<< "It was " << answers[question_choice] << endl;
strcpy( questions[counter], questions[question_choice] );
strcpy( answers[counter], answers[question_choice] );
counter++;
}
else
{
cout << endl << "Correct" << endl;
counter--;
strcpy( questions[question_choice], questions[counter] );
strcpy( answers[question_choice], answers[counter] );
}
}
cout << endl << "You Win!!!!" << endl;
return 0;
}
questions.dat would have data like this
In what year was the Pendleton Civil Service Reform Act enacted?
a.1873
b.1883
c.1893
d.1903,b
In what year did Hurricane Katrina occur?
a.2001
b.2003
c.2005
d.2007,c
I am creating a school project but seems lost at the moment. Can someone help me figure out my problem? Here's what's going on:
I have a program that outputs a random generated numbers in a text file using ofstream. It is generated with a format of two columns (one column is SalePrice & the second column RegularPrice). My problem is creating a code that will do the following:
Create a function that will read the text file generated by the first program
Find the average of the second column ONLY! (Regular Price) then outputs it in the screen
Find the minimum and maximum of the second column ONLY! (Regular Price) then outputs it in the screen
Please help! I need help how to code the ifstream part, I am new to C++ and have tried all the solutions in many books but doesn't seem to work for my needs? :-( Any help will be greatly appreciated! Thanks in advance!
Here's just the section of my code (not the entirety), it is not giving me an error . . . it is simply not giving me anything:
float SalePrice[userInput];
float RegularPrice;
string cPrice;
string readFile;
int count = 0;
ifstream inputFile;
inputFile.open(fileName);
inputFile >> RegularPrice;
// To get you all the lines and place the line from myfile into the line variable
while(!inputFile.eof() && getline(inputFile, readFile))
{
if (count < userInput)
{
inputFile >> readFile;
readFile += cPrice; // Saves the line in STRING.
//display the line we gathered:
cout << cPrice << endl;
}
++count;
}
avgRPrice = RegularPrice / userInput;
cout << endl;
cout << fixed << setprecision (2);
cout << "The average of all the Regular Prices in the file is: " << avgRPrice << endl;
cout << "The minimum Regular Price in the file is: " << minRPrice << endl;
cout << "The maximum Regular Price in the file is: " << maxRPrice << endl;
EDITED:
Here's my current code for finding the max & min:
int maxRPrice(float RPrice[])
{
if (RPrice > maxRPrice)
maxRPrice = RPrice;
return maxRPrice;
}
int minRPrice(float RPrice[])
{
if (RPrice < minRPrice)
minRPrice = RPrice;
return minRPrice;
}
Here is an improved version of your code which works perfectly for me:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int userInput = 2;
float SalePrice[userInput]; //Make an array
float RegularPrice[userInput]; //Make an array
string readFile;
ifstream inputFile;
inputFile.open("yourFile.txt");
if(!inputFile){ //Check wether the file is open
cout<<"Couldn't open file!" << endl;
return -1;
}
// To get you all the lines and place the line from myfile into the line variable
for(int count = 0; !inputFile.eof() && (count < userInput) ; ++count) //Why are you using a while-loop if you need to count the iterations
{
//
inputFile >> SalePrice[count] >> RegularPrice[count]; //loads column SalePrice/RegularPrice into the array at position 'count'
}
float sumRegularPrice = 0;
for(int i=0; i < userInput; i++)
sumRegularPrice += RegularPrice[i];
float avgRPrice = sumRegularPrice / userInput;
cout << endl;
cout << fixed;
cout << "The average of all the Regular Prices in the file is: " << avgRPrice << endl;
//cout << "The minimum Regular Price in the file is: " << minRPrice << endl;
//cout << "The maximum Regular Price in the file is: " << maxRPrice << endl;
system("pause");
return 0;
}
Why are you loading RegularPrice only once? As far as I got your explanation about the file format (you said one column is SalePrice & the second column RegularPrice), every line might have this content:
3.44 5.99
To get the min and max price you can simply write two functions.
With this input:
3.44 5.99
5.54 8.99
I get this output (in the console):
The average of all the Regular Prices in the file is: 7.490000
If you have some questions don't hesitate to ask me.