Writing function output to a text file? - c++

I'm making a program that reads a set of names and numbers from one file, expresses the numbers as a ratio, then prints them out to the terminal. I would like to know how I could redirect the output of my functions to a separate file. I have an output file ready, but am unsure of how to redirect my functions' outputs to it.
I didn't include the functions themselves here, which work fine - just the calls.
int main(){
ifstream input;
ofstream output;
string inputname, outputname, name;
int num1, num2;
cout<<"Input file?\n";
cin>>inputname;
cout<<"Output file?\n";
inFile.open(inputname.c_str());
cin>>outputfile;
outFile.open(outputname.c_str());
while(!input.eof()&&!output.eof()){
input>>name>>num1>>num2;
lists (name);
value (num1, num2);
}
input.close()
output.close()
return 0;
}

Have a look at Input/Output with files
Example:
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
As you see, it's very similar to how you're getting the data from fileA.

You have multiple undefined variables (Always test your program before posting!). And you're not checking for eof on the input file correctly. You need to test for eof right after a read operation to see if it succeeded.
int main(){
cout << "Input file?\n";
string inputname;
cin >> inputname;
ifstream input(inputname.c_str());
if (!input) return 1; // handle error however you wish
cout << "Output file?\n";
string outputname;
cin >> outputname;
ofstream output(outputname.c_str());
if (!output) return 2;
while (1) {
string name;
int num1, num2;
input >> name >> num1 >> num2;
if (!input) break;
lists(name);
value(num1, num2);
}
return 0;
}

Related

Trying to read a .txt file and pull out a specific line based off of a letter entered by user

I have this file with information from the periodic table in a .txt file and Im trying to write a program that allows the user to input the element symbol then read through the file until it finds that symbol and spits out information about that element. At first I got the program to output the cout statement with no information, and now its completely skipping this section after the symbol is entered and going right to the next. Here is my code.
ifstream fin;
ofstream myfile;
string line;
myfile.open("txt file");
fin.open("txt file", ios::app);
while (std::getline(fin, line)) {
fin >> element >> symbol >> atomic_number >> atomic_mass >> physical_state >> density >> melting_point >> boiling_point >> created >> chemical_group >> electronegativity;
if (line == symbol)
{
cout << "information from above"
break;
}
fin.close();
myfile.close();
}
Trying to read a .txt file and pull out a specific line based off of a letter entered by user.
Here is a sample code:
#include <iostream>
#include"string"
#include <fstream>
using namespace std;
int main(void)
{
ifstream fi("1.txt", ofstream::in);
ofstream fo("2.txt", ofstream::out);
string buf;
string s1;
cin >> s1;
while (fi >> buf)
{
if (buf.find(s1) != string::npos) break;
}
fo << buf << endl;
fi.close();
fo.close();
return 0;
}
1.txt is the file you are trying to read. Save the pull out specific line to 2.txt. "s1" is the string entered by the user.
Hope this code is helpful to you.

C++ while loop Issues

I am trying to read lines of a file (cityName, hiTemp, loTemp) into a struct array. I was able to use >> to read the first several lines until I hit a city with a space in it's name.
I then tried using getline() to read the lines, but then my while loop stopped working.
I have no clue why this would happen.
int LoadData()
{
int count = 0;
string path;
cout << "Specify the input file path: ";
ifstream inFile;
cin >> path;
inFile.open(path.c_str());
if (!inFile.is_open())
{
cout << "Error - could not open file: " << path;
return (-1);
}
else
{
while (!inFile.eof())
{
cities[count].city = "";
getline(inFile, cities[count].city);
if (cities[count].city.length() == 0)
{
break;
}
char comma;
inFile >> (cities[count].high) >> comma >> cities[count].low;
cout << cities[count].city << " " << cities[count].high << " " << cities[count].low << endl;
count++;
}
inFile.close();
inFile.clear(std::ios_base::goodbit);
return count;
}
}
while (!inFile.eof())
For getting every line in the file, you should use:
while(getline(inFile, cities[count].city)) {
// ...
This works and is recommended over using the .eof() method.
You can also use this in your if-statement:
if (!getline(inFile, str))
break;
As an aside, you can read this site:
Why is “while ( !feof (file) )” always wrong? - StackOverflow post
It gives insight into why using the .eof() is not the preferred method to use in a while loop to check whether the end-of-file has been reached.
Use getline as loop condition. You can also replace the second read with a getline too and use a stringstream to parse it.
#include <sstream>
// ...
while(getline(inFile, cities[count].city)) {
if (cities[count].city.empty()) break;
// read next line with high and low values
string str;
if (!getline(inFile, str)) break; // error in file format
stringstream ss(str);
char comma;
ss >> cities[count].high >> comma >> cities[count].low; // parse it
}

ifstream won't open file after selecting menu choice

So my main code is a menu.
BankAccount BA;
ifstream fin;
int UserAction = -1;
while (UserAction != 0) {
cout << "menu here";
cin >> UserAction;
if (UserAction == 1)
BA.getInstance(BA); //Input by keyboard. Works fine.
if (UserAction == 2)
BA.getInstance(BA, fin); //Input by file.
}
If I were to choose option #2, it would execute this code:
void BankAccount::getInstance(BankAccount &BA, ifstream &fin) {
string actN, fname, lname, InputFileName;
double bal;
fin.sync();
cout << "Please enter input file path: ";
getline(cin, InputFileName);
if (fin.fail())
cout << "failed";
else {
fin.open(InputFileName.c_str());
BA.getInstance(BA, fin);
}
fin >> actN;
fin >> lname;
fin >> fname;
fin >> bal;
BA = BankAccount(actN, lname, fname, bal);
}
After entering the file path, and pressing enter, it would say failed and kick me to menu. If I put cin.sync(); where fin.sync is, it would just keep looping me to enter in the file path. Note that it works outside the menu though. How would I fix it so that it would open the file path correctly without issues so it could process the information?
1 - change your main code to do-while, idk why people opt for while loops in such scenarios.
do{
cout << "menu here";
cin >> UserAction;
if (UserAction == 1)
BA.getInstance(BA); //Input by keyboard. Works fine.
if (UserAction == 2)
BA.getInstance(BA, fin); //Input by file.
} while(UserAction!=0);
2 - fin.fails because it isn't initialized, remove that line and it will work fine. try to use fin.fail() after fin.open();

How to read string, char , int all from one file untill find eof in c++?

What's wrong with my code? I want to get intput from file (first one string, then a char , then int). I want it for whole file. Here is my code. This is giving me so pain. What can i do? Please help me.
//file handling
//input from text file
//xplosive
#include<iostream>
#include<fstream>
using namespace std;
ifstream infile ("indata.txt");
int main()
{
const int l=50;
//string t_ques;
char t_ques[l];
char t_ans;
int t_time_limit;
while(!infile.eof())
//while(infile)
{
infile.getline(t_ques,l);
//infile >> t_ans ;
infile.get(t_ans);
infile >> t_time_limit;
cout << t_ques << endl;
cout << t_ans << endl;
cout << t_time_limit << endl;
}
return 0;
}
my indata.txt file contain
what is my name q1?
t
5
what is my name q2?
f
3
what is my name q3?
t
4
what is my name q4?
f
8
out put should be the same.
but my while loop don't terminate.
A number of things:
eof checking isn't appropriate (most of the time). Instead, check stream state
don't use read as it won't skip whitespace
after your timelimit, ignore input until the end of the line
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream infile ("indata.txt");
std::string t_ques;
char t_ans;
int t_time_limit;
std::getline(infile, t_ques);
while (infile >> t_ans >> t_time_limit)
{
cout << t_ques << endl;
cout << t_ans << endl;
cout << t_time_limit << endl;
infile.ignore();
std::getline(infile, t_ques);
}
}
See it live on Coliru
Try to use this expression:
infile.open("indata.txt", ios::in);
// ...same loop...
infile >> t_ques >> t_ans >> t_time_limit;
// At the end close the file
infile.close();

How to read and write to a text file in C++?

Hey everyone, I have just started to learn C++ and I wanted to know how to read and write to a text file. I have seen many examples but they have all been hard to understand/follow and they have all varied. I was hoping that someone here could help. I am a total beginner so I need clear instructions. Here is an example of what i'm trying to do:
#include <iostream>
#include <fstream>
using namespace std;
string usreq, usr, yn, usrenter;
int start ()
{
cout << "Welcome..."
int main ()
{
cout << "Is this your first time using TEST" << endl;
cin >> yn;
if (yn == "y")
{
ofstream iusrfile;
ofstream ousrfile;
iusrfile.open("usrfile.txt", "w");
iusrfile >> usr;
cout << iusrfile;
iusrfile.close();
cout << "Please type your Username. \n";
cin >> usrenter;
if (usrenter == usr)
{
start ();
}
}
else
{
cout << "THAT IS NOT A REGISTERED USERNAME.";
}
return 0;
}
Header files needed:
#include <iostream>
#include <fstream>
declare input file stream:
ifstream in("in.txt");
declare output file stream:
ofstream out("out.txt");
if you want to use variable for a file name, instead of hardcoding it, use this:
string file_name = "my_file.txt";
ifstream in2(file_name.c_str());
reading from file into variables (assume file has 2 int variables in):
int num1,num2;
in >> num1 >> num2;
or, reading a line a time from file:
string line;
while(getline(in,line)){
//do something with the line
}
write variables back to the file:
out << num1 << num2;
close the files:
in.close();
out.close();
Default c++ mechanism for file IO is called streams.
Streams can be of three flavors: input, output and inputoutput.
Input streams act like sources of data. To read data from an input stream you use >> operator:
istream >> my_variable; //This code will read a value from stream into your variable.
Operator >> acts different for different types. If in the example above my_variable was an int, then a number will be read from the strem, if my_variable was a string, then a word would be read, etc.
You can read more then one value from the stream by writing istream >> a >> b >> c; where a, b and c would be your variables.
Output streams act like sink to which you can write your data. To write your data to a stream, use << operator.
ostream << my_variable; //This code will write a value from your variable into stream.
As with input streams, you can write several values to the stream by writing something like this:
ostream << a << b << c;
Obviously inputoutput streams can act as both.
In your code sample you use cout and cin stream objects.
cout stands for console-output and cin for console-input. Those are predefined streams for interacting with default console.
To interact with files, you need to use ifstream and ofstream types.
Similar to cin and cout, ifstream stands for input-file-stream and ofstream stands for output-file-stream.
Your code might look like this:
#include <iostream>
#include <fstream>
using namespace std;
int start()
{
cout << "Welcome...";
// do fancy stuff
return 0;
}
int main ()
{
string usreq, usr, yn, usrenter;
cout << "Is this your first time using TEST" << endl;
cin >> yn;
if (yn == "y")
{
ifstream iusrfile;
ofstream ousrfile;
iusrfile.open("usrfile.txt");
iusrfile >> usr;
cout << iusrfile; // I'm not sure what are you trying to do here, perhaps print iusrfile contents?
iusrfile.close();
cout << "Please type your Username. \n";
cin >> usrenter;
if (usrenter == usr)
{
start ();
}
}
else
{
cout << "THAT IS NOT A REGISTERED USERNAME.";
}
return 0;
}
For further reading you might want to look at c++ I/O reference
To read you should create an instance of ifsteam and not ofstream.
ifstream iusrfile;
You should open the file in read mode.
iusrfile.open("usrfile.txt", ifstream::in);
Also this statement is not correct.
cout<<iusrfile;
If you are trying to print the data you read from the file you should do:
cout<<usr;
You can read more about ifstream and its API here