#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main() {
ifstream inputFile;
string fileName;
int value = 0;
int numOfNumbers = 0;
int oddNumbers = 0;
int evenNumbers = 0;
double sum = 0.0;
double average = 0.0;
int counter = 0;
//Ask user for file name
cout << "Enter file name to read: " << endl;
cin >> fileName;
//Open file
inputFile.open(fileName);
//Calculate information
if (inputFile.is_open())
{
while (inputFile >> value)
{
numOfNumbers++;
sum += value;
}
}
else
{
//Display error if file doesn't open
cout << "Error reading file." << endl;
}
if (numOfNumbers > 0)
average = sum / numOfNumbers;
else
average = 0.0;
if (numOfNumbers > 0)
{
while (inputFile >> value)
{
counter++;
if (value % 2 == 0)
evenNumbers++;
else
oddNumbers++;
}
cout << "Number of numbers = " << numOfNumbers << endl;
cout << "Average = " << average << endl;
cout << "Sum = " << sum << endl;
cout << "Number of even numbers: " << evenNumbers << endl;
cout << "Number of odd numbers: " << oddNumbers << endl;
}
else
cout << "Cannot compute values." << endl;
inputFile.close();
return 0;
}
I cannot get this program to open my file nor read the contents to do these calculations. I have moved the file into the directory and have tried typing the name with the extension (.txt). I also removed the quotations I previously had placed around fileName in inputFile.open(fileName);
Any recommendations?
Related
I'm relatively new to C++ so please excuse the use of namespace std. I'm trying to read a numeric value from a file, and determine its prime factors. Despite not failing it will ignore input, displaying an endless loop of '0' and '2is a prime number'. Below is both my code and text file.
Code:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
int div = 0, num = 0, count = 0;
string inputFile;
ifstream fin;
cout << "Enter input file name: ";
getline(cin, inputFile);
fin.open(inputFile.c_str());
if (fin.fail())
{
cout << "Bad file.\n";
cin.ignore();
getchar();
exit(0);
}
fin >> num;
cout << left << setw(12) << "Number" << setw(15) << "Prime Factors\n"
<< "---------------------------\n"
<< setw(12) << num << endl;
while (!fin.eof())
{
div = 2;
count++;
cout << setw(15) << num;
if (num < 0)
cout << "Can't do negative numbers\n"
else
{
cout << div;
while (div <= num / 2)
{
if (num % div == 0)
{
num = num / div;
cout << div;
}
else
div++;
}
}
if (div >= num / 2)
cout << "is a prime number\n";
fin.ignore(10, '\n');
fin >> num;
cout << setw(12) << num << endl;
}
if (count == 0)
cout << "No data was processed, data file is empty.\n";
cin.ignore(10, '\n');
getchar();
return (0);
}
Input.txt (Ended with a singular blank line for EoF):
348
23
I have a code that I am doing and I got the basic version to work, I need help with how to implement a function in which the program reads a text file that I have saved and reads it and outputs it based on the function. Here is my code and what I have so far..
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
//start main
int main()
{
double cost_merchandise, salary, yearly_rent, electricity_cost;
double totalCost, netProfit;
double PERCENTAGE_SALE = 0.15;
double PERCENTAGE_GOAL = 0.10;
double after_sale;
double Mark_up;
string line;
ifstream myfile ("F:/Intro To C++/ch0309.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
//gets data
cout << "Enter merchandise cost: ";
cin >> cost_merchandise;
cout << "Enter employee salary: ";
cin >> salary;
cout << "Enter yearly rent: ";
cin >> yearly_rent;
cout << "Enter the estimated electricity cost: ";
cin >> electricity_cost;
totalCost = cost_merchandise + salary + yearly_rent + electricity_cost;
//Output expenses, calculate mark ups, cost after 15%
cout << endl << setprecision(2) << fixed;
cout << "\nThe Company's expenses equals $: " << totalCost << endl << endl;
netProfit = cost_merchandise * PERCENTAGE_GOAL;
after_sale = netProfit + totalCost;
Mark_up = (after_sale - cost_merchandise) / 100;
cout << "A 10% profit is valued at $: " << netProfit << endl;
cout << "Mark Up is " << Mark_up * 100 << "%" << endl;
return 0;
}
//end of main
Here is a way to do it, assuming that your data is splited by whitespaced or new lines :
#include <string>
#include <vector>
#include <fstream>
template<typename T>
std::vector<T> getDataFromFile(const std::string& filename) {
std::ifstream file_input_stream(filename);
if (!file_input_stream)
throw std::exception("ifstream failed to open");
std::vector<T> data;
T input_data;
while (!(file_input_stream >> input_data).eof()) {
data.push_back(input_data);
}
return data;
}
and you use it like this :
auto int_vector = getDataFromFile<int>(filename);
// You can modify the template parameter with the good data type ( char, double, string... )
//To output the vector :
for (const auto& i : int_vector) {
std::cout << i;
}
I get an error saying: use of undeclared identifier 'again'.
I am trying to go from int main to void again and back after getting an answer.
Please explain to me why it won't work also. Thanks.
Here is my full code:
#include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <string>
using namespace std;
{
string answer;
cout << "Would you like to enter another set of data? Y or N?" << endl;
cin << answer;
string yes = "Yes";
string no = "No";
if(a == yes)
{
main();
}
}
int main()
{
cout << "Kaitlin Stevers" << endl;
cout << "Exercise 11 - Vectors" << endl;
cout << "November 12, 2016" <<endl;
cout << endl;
cout << endl;
int size;
cout << " How many numbers would you like the vector to hold? " << endl;
cin >> size;
vector<int> numbers;
int bnumbers;
for (int count = 0; count < size; count++)
{
cout << "Enter a number: " << endl;
cin >> bnumbers;
numbers.push_back(bnumbers); // Adds an element to numbers
}
//display the numbers stored in order
cout << "The numbers in order are: " << endl;
for(int bcount = 0; bcount < size; bcount++)
{
cout << numbers[bcount] << " ";
}
cout << endl;
//display the numbers stored reversed
cout << "Here are the numbers in reverse order: " << endl;
reverse(numbers.begin(), numbers.end());
for(int rcount = 0; rcount < size; rcount++)
{
cout << numbers[rcount] << " ";
}
cout << endl;
again();
return 0;
}
void again()
}
You need to declare your fonction "again" before calling it :
#include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <string>
using namespace std;
void again();
int main()
{
cout << "Kaitlin Stevers" << endl;
cout << "Exercise 11 - Vectors" << endl;
cout << "November 12, 2016" <<endl;
cout << endl;
cout << endl;
int size;
cout << " How many numbers would you like the vector to hold? " << endl;
cin >> size;
vector<int> numbers;
int bnumbers;
for (int count = 0; count < size; count++)
{
cout << "Enter a number: " << endl;
cin >> bnumbers;
numbers.push_back(bnumbers); // Adds an element to numbers
}
//display the numbers stored in order
cout << "The numbers in order are: " << endl;
for(int bcount = 0; bcount < size; bcount++)
{
cout << numbers[bcount] << " ";
}
cout << endl;
//display the numbers stored reversed
cout << "Here are the numbers in reverse order: " << endl;
reverse(numbers.begin(), numbers.end());
for(int rcount = 0; rcount < size; rcount++)
{
cout << numbers[rcount] << " ";
}
cout << endl;
again();
return 0;
}
void again()
{
string answer;
cout << "Would you like to enter another set of data? Y or N?" << endl;
cin >> answer;
string yes = "Yes";
string no = "No";
if(answer == yes)
{
main();
}
}
However, it's a strange things to use recursivity for what you want to do and to call main func multiple times (which is by definition, main entry of a program). In my opinion, you should call in your main function another function named like askInformation which uses a loop with a test case to know if user wants to add informations or not.
Right now my problem seems to be focused on the saveFile function.
I will post the entire program here, so dont be ired when see a whole bunch of code... just look at the saveFile function at the bottom... I am posting all the code JUST IN CASE it will help you help me solve my problem.
Now for defining the apparent problem to you all: I can edit the file throughout the life of the console app with the updateSale function as I run it, but when I use the saveFile function and put in 'y' to save, the differences that are visible after using the updateSales function DO NOT get saved to the actual sales file called "salespeople.txt" and I do not understand why.
this is what the salespeople.txt looks like:
Schrute 25000
Halpert 20000
Vance 19000
Hudson 17995.5
Bernard 14501.5
now here is the program:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
//variables--------------------------------------------------------
int lineCount = 0;
//prototypes-------------------------------------------------------
int getIndexLargest(string[], double[]);
void displaySalesPeople(string[], double[]);
bool readSalesFile(string[], double[]);
void updateSales(string[], double[]);
int saveFile(string, string[], double[], int);
int main()
{
string fileName;
int arrayLength;
ifstream readSales;
string salesPersonName[5];
double saleAmount[5];
bool flag = false;
int options;
do
{
cout << "1) Open sales person file. "<< endl;
cout << "2) Display sales person information. "<< endl;
cout << "3) Update sales. " << endl;
cout << "4) Get best sales person. " << endl;
cout << "5) Exit. " << endl;
cout << "Please enter a number 1-5 to select an option." <<endl;
cin >> options;
if(options == 1)
{
flag = readSalesFile(salesPersonName, saleAmount);
}
else if(options == 2)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
displaySalesPeople(salesPersonName, saleAmount);
}
else if(options == 3)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
updateSales(salesPersonName, saleAmount);
}
else if(options == 4)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
getIndexLargest(salesPersonName, saleAmount);
}
else if(options == 5)
{
char choice;
cout << "Enter character y to save... anything else will exit without saving: " << endl;
cin >> choice;
if(choice == 'y')
{
saveFile(fileName, salesPersonName, saleAmount, arrayLength);
cout << "File saved. " << endl;
}
else
{
cout << "closing program" << endl;
}
}
}
while(options != 5);
return 0;
}
//functions---------------------------------
bool readSalesFile(string salesPersonName[], double saleAmount[])
{
bool flag = false;
ifstream readSales;
string fileName;
cout << "Please enter the path to your sales people file: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
while(readSales.fail())
{
cout << "Failed. Please enter the path to your sales file again: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
}
if(readSales.good())
{
flag = true;
cout << lineCount;
string name = " ";
double amount =0.00;
int i = 0;
while(!readSales.eof())
{
readSales >> name;
readSales >> amount;
salesPersonName[i] = name;
saleAmount[i] = amount;
i++;
}
for(i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
readSales.close();
}
readSales.close();
return flag;
}
void displaySalesPeople(string salesPersonName[], double saleAmount[])
{
for(int i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
}
void updateSales(string salesPersonName[], double saleAmount[])
{
bool flag = false;
string findName;
double moneyAmount;
cout << "Enter name of sales person you want to modify: " << endl;
cin >> findName;
for(int i = 0; i < 5; i++)
{
if(findName == salesPersonName[i])
{
cout << "Enter the sale amount you would like to modify: " << endl;
cin >> moneyAmount;
saleAmount[i] += moneyAmount;
cout << saleAmount[i] << endl;
flag = true;
}
}
if(flag == false)
{
cout << " name not found" << endl;
}
}
int getIndexLargest(string salesPersonName[], double saleAmount[])
{
ifstream readSales;
while(!readSales.eof())
{
double largestSale = 0.00;
string largestSalesPerson;
int i = 0;
lineCount++;
readSales >> salesPersonName[i];
readSales >> saleAmount[i];
if(saleAmount[i] > largestSale)
{
largestSale = saleAmount[i];
largestSalesPerson = salesPersonName[i];
}
cout << "Best sales person : "<< largestSalesPerson << " $" <<setprecision(2)<<fixed<< largestSale << endl;
}
}
int saveFile(string fileName, string salesPersonName[], double saleAmount[], int arrayLength)
{
ofstream saveFile(fileName.c_str());
saveFile.open(fileName.c_str());
for(int i = 0; i < 5; i++)
{
saveFile << salesPersonName[i] << " " << saleAmount[i] << endl;
}
saveFile.close();
return 0;
}
You are trying t open your file twice:
ofstream saveFile(fileName.c_str()); // this opens the file
saveFile.open(fileName.c_str()); // so does this
That will put the file in an error state so no writing will happen.
Just do this:
ofstream saveFile(fileName.c_str()); // this opens the file
And that should work.
Or else you can do this:
ofstream saveFile; // this does not open the file
saveFile.open(fileName.c_str()); // but this does
And that should work too.
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream fout1;
ofstream fout2;
string fnameOdd;
string fnameEven;
int x;
int numEven(0);
int numOdd(0);
cout << "Enter name of file for odd integers: ";
getline(cin, fnameOdd);
fout1.open(fnameOdd.c_str(), ios::out);
cout << "Enter name of file for even integers: ";
getline(cin, fnameEven);
fout2.open(fnameEven.c_str(), ios::out);
if(!fout1.is_open())
{
cerr << "Unable to open file" << fnameOdd << endl;
exit(10);
}
if(!fout2.is_open())
{
cerr << "Unable to open file" << fnameEven << endl;
exit(15);
}
cout << "Enter list of odd and even integers (followed by 0): " << endl;
cin >> x;
while (x != 0)
{
if (x % 2 == 0)
{
numEven++;
}
else
{
numOdd++;
}
}
fout1 << numEven;
fout2 << numOdd;
cout << "File " << fnameOdd << " contains " << numOdd << " odd integers. " <<endl;
cout << "File " << fnameEven << " contains " << numEven << " even integers. " <<endl;
fout1.close();
fout2.close();
return 0;
}
I am having trouble outputting anything to the screen, nothing is happening it is just inputting the file names and integers. i am not sure how to output what i have wrote onto the file, and reading my book does not help.
You forget that your input statement cin >> x; needs to go inside the loop as well
cin >> x;
while (x != 0)
{
if (x % 2 == 0)
{
numEven++;
}
else
{
numOdd++;
}
cin >> x; // new line here
}
The way you wrote it after you input the first value for x, it never changes it's value again. So the while loop never ends. That's why you didn't see any output.