Reading from text file with ifstream - c++

So I am trying to read from a text file. It shows that I can successfully read from the file But when I try to cout the values, it just shows 0, while I have other values in the text file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
std::ifstream file("numbers.txt");
if (file) {
cout << "Managed to read file successfully. \n";
}else{
cout << "Unable to read file.";
}
int x, y;
file >> x >> y;
cout << "Num 1: " << x << endl;
cout << "Num 2: " << y << endl;
return 0;
}

With the numbers.txt file
45
15
Your code work find with gcc.
int main()
{
std::ifstream file("numbers.txt");
if (file)
{
cout << "Managed to read file successfully. \n";
int x, y;
file >> x >> y;
cout << "Num 1: " << x << endl;
cout << "Num 2: " << y << endl;
}
else
{
cout << "Unable to read file.";
}
return 0;
}

The above code will print status of your operation,if you want to read and display contents the you have to write your code like this:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream stream1("D:\\file1.txt");
char a[80];
if(!stream1)
{
cout << "While opening a file an error is encountered" << endl;
}
else
{
cout << "File is successfully opened" << endl;
}
while(!stream1.eof())
{
stream1 >> a;
cout << a << endl;
}
return(0);
}

Related

How to get input file to go into an array

I'm trying to get information from an input file into an output file, which I have done, but I can't figure out how to get the numbers from the file into an array and only output the numbers divisible by 7. I've been stuck for a few hours, please help.
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
using namespace std;
int main()
{
string ifilename, ofilename, line;
ifstream inFile, checkOutFile;
ofstream outFile;
char response;
// Input file
cout << "Please enter the name of the file you wish to open : ";
cin >> ifilename;
inFile.open(ifilename.c_str());
if (inFile.fail())
{
cout << "The file " << ifilename << " was not successfully opened." << endl;
cout << "Please check the path and name of the file. " << endl;
exit(1);
}
else
{
cout << "The file is successfully opened." << endl;
}
// Output file
char array[10];
int numberz = 0;
cout << "Please enter the name of the file you wish to write : ";
cin >> ofilename;
checkOutFile.open(ofilename.c_str());
if (!checkOutFile.fail())
{
cout << "A file " << ofilename << " exists.\nDo you want to continue and overwrite it? (y/n) : ";
cin >> response;
if (tolower(response) == 'n')
{
cout << "The existing file will not be overwritten. " << endl;
exit(1);
}
}
outFile.open(ofilename.c_str());
if (outFile.fail())
{
cout << "The file " << ofilename << " was not successfully opened." << endl;
cout << "Please check the path and name of the file. " << endl;
exit(1);
}
else
{
cout << "The file is successfully opened." << endl;
}
// Copy file contents from inFile to outFile
while (getline(inFile, line))
{
fscanf(ifilename, &array[numberz]);
cout << line << endl;
outFile << line << endl;
}
// Close files
inFile.close();
outFile.close();
} // main
I'd use boost::filesystem for that task.
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
namespace fs = boost::filesystem;
int main()
{
fs::path ifilename;
std::cout << "Input file: ";
std::cin >> ifilename;
fs::ifstream inFile{ifilename};
if ( inFile.fail() )
throw std::invalid_argument("Could not open file");
fs::path ofilename;
std::cout << "Output file: ";
std::cin >> ofilename;
if ( fs::exists(ofilename) )
{
std::cout << ofilename << " exists. Do you want to overwrite it? (y/n) ";
char response;
std::cin >> response;
if ( ! ( response == 'y' || response == 'Y' ) )
return 1;
}
fs::ofstream outFile{ofilename};
if ( outFile.fail() )
throw std::invalid_argument("Could not open file");
std::vector<std::string> array;
std::string line;
while ( std::getline(inFile, line) )
{
array.push_back( line );
std::cout << line << '\n';
outFile << line << '\n';
}
inFile.close();
outFile.close();
}

Weird symbol when reading file in C++

I'm using fstream to access a file and extract its contents. When I go to output its data I continue to get just one weird symbol. This is the process I'm using. I've used it before with success but now I seem to have an issue. Here is the code.
#include<iostream>
#include<fstream>
using namespace std;
int main() {
char text;
int waitForIt;
fstream Txt1("In.txt", ios::in);
cout << "\n\tcontents of In.txt:" << endl << endl;
cout << "\t\t";
Txt1.get(text);
do {
cout << text;
Txt1.get(text);
} while (!Txt1.eof());
Txt1.close();
cin >> waitForIt;
};
This is what is being output:
I bet your file could not be opened. The way you wrote your loop, you print the character you think you had read by using get function even if reading failed.
You should do:
fstream Txt1("In.txt", ios::in);
if ( Txt1.is_open() )
{
cout << "\n\tcontents of In.txt:" << endl << endl;
cout << "\t\t";
while (!Txt1.eof())
{
Txt1.get(text);
cout << text;
}
Txt1.close();
}
else
{
cout << "Unable to open file" << endl;
}

How to Ifstream codeblocks on mac?

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
inFile.open("test.txt");
int foo;
string sFoo;
inFile >> sFoo;
inFile >> foo;
cout << "the name is " << sFoo << endl;
cout << "the first number is " << foo << endl;
inFile >> foo;
cout << "the second number is " << foo << endl;
cout << "Hello World!";
return 0;
}
I have tried putting my text file in the same folder. However, for some reason it is not able to read the text file. Please can someone tell me what to do in codeblocks on macbook to make this happen!
You have to write full absolute path of your file and not relative. I've answered the same question here.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
inFile.open("/Users/user/Desktop/test.txt");
if(inFile){
int foo;
string sFoo;
inFile >> sFoo;
inFile >> foo;
cout << "the name is " << sFoo << endl;
cout << "the first number is " << foo << endl;
inFile >> foo;
cout << "the second number is " << foo << endl;
cout << "Hello World!";
inFile.close();
}else{
cout<<"unable to open file"<<endl;
}
return 0;
}

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);
}

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.