CSV file is not getting data from buffor - c++

I'm learning to code in C++ and I'm doing some examples of file operations. There is no problem to send to file text data when it is saved as .txt file.
However I went further and experiment on csv files:
#include <iostream>
#include <string>
#include <fstream>
#include <math.h>
#include <stdio.h>
using namespace std;
int main ()
{
int num = 0;
fstream file;
string file_name;
cout << "Input file name: ";
cin>>file_name;
file.open(file_name.c_str());
if (file.fail())
{
cout << "Unable to open file - try again" << endl;
main ();
} else
{
file << "VALUE" << "\t" << "1/x" << "\t" << "sqrt" << endl;
while (num < 200)
{
file << num << "\t" << 1/num << "\t" << sqrt(num) << endl;
num ++;
}
file.close();
return 0;
}
}
When I'm checking the file - there is only header:
enter image description here
What should I do to write into this csv file - results of these mathematical operations?

See my comment regarding division by zero. Also do not use integers for division. Change
while (num < 200)
{
file << num << "\t" << 1/num << "\t" << sqrt(num) << endl;
num ++;
}
to
while(num < 200)
{
num++;
file << num << "\t" << 1.0 / num << "\t" << sqrt(num) << endl;
}

Related

C++ program not able to open files from user input

#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?

Directing output into a .txt file in C++

How do I direct the output of this code into a .txt file?
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
int main() {
using std::cin;
using std::cout;
using std::endl;
int input=1;
int sum=0;
int counter=1;
while (input != 0)
{
std::cout << "Please enter the hit data: ";
std::cin >> input;
if (input == 0) // after puting in data input zero
{
break;
}
else if (input != 0)
{
sum += input;
counter++;
}
}
counter = counter - 1 ;
std::cout << "Sum of hits entered: " << sum << endl ;
std::cout << "Number of hits entered: " << counter << endl ;
if ( counter < 100 )
{
std::cout << "The hits are less than 100" ;
}
else if ( counter > 100 )
{
std::cout << "The hits are greater than 100" ;
}
else if ( counter == 100 )
{
std::cout << "The hits are equal to 100" ;
}
}
Also, instead of a user having to input data, how can I get the program to read data from another .txt file? I understand you can do this all easily in the terminal; however, I would like for the program to create the .txt file.
Also, how do I get the program to recognize certain numbers? I want it to output something like "there was twelve number -11s counted".
Use std::ifstream to read input from a file, and std::ofstream to write output to a file. For example:
#include <iostream>
#include <fstream>
int main()
{
int sum = 0;
int counter = 0;
std::ifstream in("hits.txt");
if (in.is_open())
{
while (in >> input)
{
sum += input;
++counter;
}
}
else
{
std::ofstream out("hits.txt");
int input;
do
{
std::cout << "Please enter the hit data: ";
// after putting in data, input zero
if (!(std::cin >> input) || (input == 0))
break;
out << input << " ";
sum += input;
++counter;
}
while (true);
}
std::cout << "Sum of hits entered: " << sum << endl ;
std::cout << "Number of hits entered: " << counter << endl ;
if (counter < 100)
{
std::cout << "The hits are less than 100" << std::endl;
}
else if (counter > 100)
{
std::cout << "The hits are greater than 100" << std::endl;
}
else
{
std::cout << "The hits are equal to 100" << std::endl;
}
return 0;
}
Also, how do I get the program to recognize certain numbers? I want it to output something like "there was twelve number -11s counted".
You can use std:map for that, eg:
#include <iostream>
#include <fstream>
#include <map>
int main()
{
int sum = 0;
int counter = 0;
std::map<int, int> hits; // hit counter
std::ifstream in("hits.txt");
if (in.is_open())
{
while (in >> input)
{
hits[input]++;
sum += input;
++counter;
}
}
else
{
std::ofstream out("hits.txt");
int input;
do
{
std::cout << "Please enter the hit data: ";
// after putting in data, input zero
if (!(std::cin >> input) || (input == 0))
break;
out << input << " ";
hits[input]++;
sum += input;
++counter;
}
while (true);
}
std::cout << "Sum of hits entered: " << sum << endl ;
std::cout << "Number of hits entered: " << counter << endl ;
if (counter < 100)
{
std::cout << "The hits are less than 100" << std::endl;
}
else if (counter > 100)
{
std::cout << "The hits are greater than 100" << std::endl;
}
else
{
std::cout << "The hits are equal to 100" << std::endl;
}
for (auto &p : hits)
{
if (p.second == 1)
std::cout << "there was 1 number " << p.first << " counted" << std:::endl;
else
std::cout << "there were " << p.second << " number " << p.first << "'s counted" << std:::endl;
}
/* or, if you are not using C++11 or later:
for (std::map<int, int>::iterator iter = hits.begin(); iter != hits.end(); ++iter)
{
std::map<int, int>::value_type &p = *iter;
if (p.second == 1)
std::cout << "there was 1 number " << p.first << " counted" << std:::endl;
else
std::cout << "there were " << p.second << " number " << p.first << "'s counted" << std:::endl;
}
*/
return 0;
}
Outputting data to a .txt file is easy indeed. You already included , now you need to create an object from the type std::ofstream and use it to write your text into a file. I would create a function like this (above main):
#include <iostream>
#include <fstream>
#include <string>
void outputTextToFile (std::string p_text) {
//is created under your project filepath:
std::ofstream file("nameoffile.txt", std::ios::app); //"app" = appending, instead of overwriting text
file << "Writing this to a file.\n";
file.close();
}
Afterwards you can call your function in the while loop with the string text you want, like this for example:
outputTextToFile("test Text");
Reading text from a .txt file is very similar to this, I would suggest you look up this thread: Read file line by line

Search and edit .txt fstream files according to ID/ Registration

I am trying to search a specific ID/ registration from a .txt and display the corresponding info accordingly. In this case I want to display the pricing according to the corresponding registration number which should be entered.
Reading and writing files is not the issue for me. There is a lot of info on the web in regards with reading and writing, but not much on searching and displaying according to the ID/ registration.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
string line;
double cost;
string reg;
ifstream in_stream;
ofstream out_stream;
char registration[10];
//Open file
in_stream.open("Fines.dat");
//Error if opening fails
if (in_stream.fail())
{
cout << "Input file could not open. " << endl;
exit(1);
}
//Open out stream file
out_stream.open("OutStandingFines.dat");
//Error if opening fails
if (out_stream.fail())
{
cout << "Output file opening failed.\n";
exit(1);
}
//Display original .dat file
cout <<"Original .dat File" << endl;
if(in_stream.is_open())
{
while(in_stream >> reg >> cost)
{
cout << reg <<" " << cost << '\n';
}
in_stream.close();
}
else
{
cout <<"File is not open: " << endl;
}
/////////////My problem is from here//////////////////////////
//Enter the registration number you wish to search
cout << "Please enter registration number: " << endl;
cin >>registration;
//I must display all cost values that have the same registration number???????? I need help with this
/*
for (int i = 0; i < 10; i++)
{
if( reg == registration)
{
cout << fixed << setw(2)<< setprecision(2) <<"R " << cost << '\n';
out_stream << fixed << setw(2)<< setprecision(2) << "R "<< cost << endl; //send back to .dat
}
}
*/
in_stream.close();
out_stream.close();
system("pause");
return(0);
}
Ok, I managed to get the output. The problem I have now is to display all the values with the same registration/ ID.
For some reason only the last row in the fstream .txt gets displayed when I enter "ABC123".
The input .txt contains the following info.
ABC123 400
DEC234 340
ABC123 500
GED345 600
ABC123 240
GEE600 120
GED345 230
GEE600 470
ABC123 120
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
string line;
double cost;
string reg;
ifstream in_stream;
ofstream out_stream;
string registration;
in_stream.open("Fines.dat");
if (in_stream.fail())
{
cout << "Input file could not open. " << endl;
exit(1);
}
out_stream.open("OutStandingFines.dat");
if (out_stream.fail())
{
cout << "Output file opening failed.\n";
exit(1);
}
//Display original .dat file
cout <<"Original .dat File" << endl;
if(in_stream.is_open())
{
while(in_stream >> reg >> cost)
{
cout << reg <<" " << cost << '\n';
}
}
else
{
cout <<"File is not open: " << endl;
}
//Enter Registration here
cout << "Please enter registration number: " << endl;
cin >>registration;
//compare and display all registration numbers that match
cout <<"Fines: " << endl;
if(out_stream.is_open())
{
while(reg == registration)
{
cout << fixed << setw(2)<< setprecision(2) <<"R " << cost << '\n';
out_stream << fixed << setw(2)<< setprecision(2) << "R "<< cost << endl; //send back to .dat
exit(1);
}
}
else
{
cout <<"File is not open: " << endl;
}
in_stream.close();
out_stream.close();
system("pause");
return(0);
}

file setprecision c++ code

I had this code in C++ that is working just fine, first it ask the user for a
file name, and then saves some number in that file.
But what I am trying to do is to save numbers with two decimal places, e.g the
user types 2 and I want to save the number 2, but with two decimal places
2.00.
Any ideas of how to do that?
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
double num;
double data;
string fileName = " ";
cout << "File name: " << endl;
getline(cin, fileName);
cout << "How many numbers do you want to insert? ";
cin >> num;
for (int i = 1; i <= num; i++) {
ofstream myfile;
myfile.open(fileName.c_str(), ios::app);
cout << "Num " << i << ": ";
cin >> data;
myfile << data << setprecision(3) << endl;
myfile.close();
}
return 0;
}
Ok, you need to use setprecision before the data is written.
I would also move the open and close of the file out of the loop (and the declaration of myfile, of course, as it's generally a fairly "heavy" operation to open and close a file inside a loop like this.
Here's a little demo that works:
#include <iostream>
#include <fstream>
#include <iomanip>
int main()
{
std::ofstream f("a.txt", std::ios::app);
double d = 3.1415926;
f << "Test 1 " << std::setprecision(5) << d << std::endl;
f << "Test 2 " << d << std::endl;
f << std::setprecision(7);
f << "Test 3 " << d << std::endl;
f.precision(3);
f << "Test 3 " << d << std::endl;
f.close();
}
Note however that if your number is for example 3.0, then you also need std::fixed. E.g. if we do this:
f << "Test 1 " << std::fixed << std::setprecision(5) << d << std::endl;
it will show 3.00000

having trouble outputting what i wrote to a file

#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.