reading from a text file that contains numbers and characters - c++

I recently learned how to read data from a text file, but I would like to continue expanding my knowledge on that matter. I would like to read files that contain numbers and characters. Can anyone give me some advice please?
The following is the code I wrote to read numbers:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
ifstream infile("input.txt", ios::in);
if (!infile) {
cout << "Inputxxxxx file could not be opened" << endl;
exit(1);
}
ofstream outfile ("outputt.txt", ios::out);
if (!outfile) {
cout << "inputssss file could not be opened " <<endl;
exit(1);
}
int number;
int answer[10];
for (int i = 0; i < 9 ; i++) {
infile >> number;
answer[i]=number;
cout << answer[i] << " ";
outfile <<answer[i]<< " ";
}
return 0;
}

Related

How to detect a new line and add it to the string. Fstream

Hello I created this program and the only problem is I don't know how to detect a new line and how to add \n to the string every time new line occurs. I'm using Visual Studio Community 2015 if it matters. Thank you!
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main() {
ofstream ofile;
ifstream ifile;
string filehold;
vector<string> data;
string line;
ofile.open("C:/Users/Nada/Desktop/data.txt");
ofile << "ph4n70m is awesome \n LOL im awesome"<< flush;
ifile.open("C:/Users/Nada/Desktop/data.txt");
if (ifile.fail()) {
cerr << "Error!" << endl;
system("pause");
exit(1);
}
while (!ifile.eof()) {
ifile >> filehold;
data.push_back(filehold);
}
cout << "data.txt: " << endl;
for (unsigned int i = 0; i < data.size(); i++) {
cout << data[i] + " ";
}
ifile.close();
system("pause");
return 0;
}
Change your reading loop to
while (std::getline(ifile,filehold)) {
filehold += '\n';
data.push_back(filehold);
}

Reading different data types in database/file(File Handling in C++)

I am doing an ATM exercise. In my database or ".txt" file I have the basic information.
0123456789 John Doe 0123 9000
The only thing I can find in the internet, reading a file in C++ is using getline();. It reads the file and stores it in a variable string. I have values like integer and float which I have to use.
How do I store the values in my database to a different data type not
just in one string?
Or is there a way of cutting the string and store the the different values in a float or integer?
Is there another way of reading? I am just new to C++ programming.
In C++,you can read file by "file stream":
#include <iostream>
#include <string>
using namespace std;
int main(){
string filename="test.txt";
ifstream fin(filename);
while (!fin.fail()){//read until end of file
int a,d,e;
string b,c;
fin>>a>>b>>c>>d>>e;//That's a line
cout<<a<<" "<<b<<" "<<c<<" "<<d<<" "<<e<<" \n";//show it on command line
}
fin.close();
return 0;
}
You can use the libary #include <fstream>. Here's a code of what it will look like in your case. In "Text.txt" I copied and pasted your inputfile.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
int firstNumber, thirdNumber, fourthNumber;
string firstString, secondString;
//Reading from a file
ifstream file;
file.open("Text.txt", ios::in);
if (file.is_open()) {
while (!file.eof()) {
file >> firstNumber >> firstString >> secondString >> thirdNumber >> fourthNumber;
cout << firstNumber << " " << firstString << " " << secondString << " " << thirdNumber << " " << fourthNumber << endl;
}
file.close();
}
else {
cout << "File did not open";
}
//Outputing to a file
ofstream file2;
file2.open("SecondText.txt", ios::out); // ios::out instead of ios::in
if (file2.is_open()) {
file2 << firstNumber << " " << firstString << " " << secondString << " " << thirdNumber << " " << fourthNumber;
file2.close();
}
else {
cout << "Problem with SecondText.txt";
}
return 0;
}
This code basically states that while open, and not at the end of the file, retrieve an Integer, String, String, Integer, and Integer, in that order for every line in that file.
If you have any questions just ask!

C++ reading from a text file into a array/string

Here is the code I have so far.
What I need to do is read from two different text files, Matrix A and Matrix B.
I can do this however for each text file matrix I read it only comes up with
1 0 0
(so basically the first line) where the whole text file for Matrix A is in fact
1 0 0
2 0 0
3 0 0
so does anybody know how I can do this?
Thanks!
#include <iostream> //declaring variables
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
string code(string& line);
int main()
{
ofstream outf;
ifstream myfile;
string infile;
string line;
string outfile;
cout << "Please enter an input file (A.txt) for Matrix A or (B.txt) for Matrix B" << endl;
cin >> infile; //prompts user for input file
if (infile == "A.txt")
{ //read whats in it and write to screen
myfile.open("A.txt");
cout << endl;
getline (myfile, line);
cout << line << endl;
}
else
if (infile == "B.txt")
{
myfile.open("B.txt");
cout << endl;
getline (myfile, line);
cout << line << endl;
}
else
{
cout << "Unable to open file." << endl;
}
//{
//while("Choose next operation");
//}
return 0;
}
Well, getline obviously gets one line.
You should read line by line until the end of file, and you can achieve that with, for example:
while (getline(myfile, line))
out << line << endl;
This means: while there is a line to get from myfile, write that line to the output stream.
You are reading only once, so this is not a miracle. You will need to use a while or for loop for continous reading. You would be writing something like this:
while (getline (myfile, line))
cout << line << endl;
This would be the whole code to write:
#include <iostream> //declaring variables
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
string code(string& line);
int main()
{
ofstream outf;
ifstream myfile;
string infile;
string line;
string outfile;
cout << "Please enter an input file (A.txt) for Matrix A or (B.txt) for Matrix B" << endl;
cin >> infile; //prompts user for input file
if (infile == "A.txt")
{ //read whats in it and write to screen
myfile.open("A.txt");
cout << endl;
while (getline (myfile, line))
cout << line << endl;
}
else
if (infile == "B.txt")
{
myfile.open("B.txt");
cout << endl;
while (getline (myfile, line))
cout << line << endl;
}
else
{
cout << "Unable to open file." << endl;
}
//{
//while("Choose next operation");
//}
return 0;
}
Using getline is the easiest way:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
void read_file_line_by_line(){
ifstream file;
string line;
file.open("path_to_file");
while (getline (file, line))
cout << line << endl;
}
int main(){
read_file_line_by_line();
return 0;
}

How to read a file into vector in C++?

I need to read from a .data or .txt file containing a new float number on each line into a vector.
I have searched far and wide and applied numerous different methods but every time I get the same result, of a Main.size() of 0 and an error saying "Vector Subscript out of Range", so evidently the vector is just not reading anything into the file.
Note: the file is both in the folder and also included in the VS project.
Anyway, here's my code:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<double> Main;
int count;
string lineData;
double tmp;
ifstream myfile ("test.data", ios::in);
double number;
myfile >> count;
for(int i = 0; i < count; i++) {
myfile >> tmp;
Main.push_back(tmp);
cout << count;
}
cout << "Numbers:\n";
cout << Main.size();
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
cin.get();
return 0;
}
The result I get is always simply:
Numbers:
0
Your loop is wrong:
for (int i=0; i=((Main.size())-1); i++) {
Try this:
for (int i=0; i < Main.size(); i++) {
Also, a more idiomatic way of reading numbers into a vector and writing them to stdout is something along these lines:
#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <algorithm> // for std::copy
int main()
{
std::ifstream is("numbers.txt");
std::istream_iterator<double> start(is), end;
std::vector<double> numbers(start, end);
std::cout << "Read " << numbers.size() << " numbers" << std::endl;
// print the numbers to stdout
std::cout << "numbers read in:\n";
std::copy(numbers.begin(), numbers.end(),
std::ostream_iterator<double>(std::cout, " "));
std::cout << std::endl;
}
although you should check the status of the ifstream for read errors.
Just to expand on juanchopanza's answer a bit...
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
does this:
Create i and set it to 0.
Set i to Main.size() - 1. Since Main is empty, Main.size() is 0, and i gets set to -1.
Main[-1] is an out-of-bounds access. Kaboom.
Just a piece of advice.
Instead of writing
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
as suggested above, write a:
for (vector<double>::iterator it=Main.begin(); it!=Main.end(); it++) {
cout << *it << '\n';
}
to use iterators. If you have C++11 support, you can declare i as auto i=Main.begin() (just a handy shortcut though)
This avoids the nasty one-position-out-of-bound error caused by leaving out a -1 unintentionally.
1.
In the loop you are assigning value rather than comparing value so
i=((Main.size())-1) -> i=(-1) since Main.size()
Main[i] will yield "Vector Subscript out of Range" coz i = -1.
2.
You get Main.size() as 0 maybe becuase its not it can't find the file. Give the file path and check the output. Also it would be good to initialize the variables.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
fstream dataFile;
string name , word , new_word;
vector<string> test;
char fileName[80];
cout<<"Please enter the file name : ";
cin >> fileName;
dataFile.open(fileName);
if(dataFile.fail())
{
cout<<"File can not open.\n";
return 0;
}
cout<<"File opened.\n";
cout<<"Please enter the word : ";
cin>>word;
cout<<"Please enter the new word : ";
cin >> new_word;
while (!dataFile.fail() && !dataFile.eof())
{
dataFile >> name;
test.push_back(name);
}
dataFile.close();
}
//file name must be of the form filename.yourfileExtension
std::vector<std::string> source;
bool getFileContent(std::string & fileName)
{
if (fileName.substr(fileName.find_last_of(".") + 1) =="yourfileExtension")
{
// Open the File
std::ifstream in(fileName.c_str());
// Check if object is valid
if (!in)
{
std::cerr << "Cannot open the File : " << fileName << std::endl;
return false;
}
std::string str;
// Read the next line from File untill it reaches the end.
while (std::getline(in, str))
{
// Line contains string of length > 0 then save it in vector
if (str.size() > 0)
source.push_back(str);
}
/*for (size_t i = 0; i < source.size(); i++)
{
lexer(source[i], i);
cout << source[i] << endl;
}
*/
//Close The File
in.close();
return true;
}
else
{
std::cerr << ":VIP doe\'s not support this file type" << std::endl;
std::cerr << "supported extensions is filename.yourfileExtension" << endl;
}
}

input/output for a file in c++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// Main Routine
void main() {
char in;
string s,m;
fstream f;
// Open file
cout << "Positive Filter Program\n"<< endl;
cout << "Input file name: ";
cin >> s;
cout << "Output file name: ";
cin >> m;
f.open(s.data(),ios::in);
f.open(m.data(),ios::out);
// Loop through file
if(f.is_open())
{
while(f.good())
{
f.get(in);
f<<in;
cout << "\nFinished!"<< endl;
}
}
else cout << "Could not open file";
// Close file
f.close();
}
I am not sure what I am doing wrong here. In this program I am trying to cin the file name that would input, and then would output onto what file name that you typed in.
The same fstream object is being reused:
f.open(s.data(),ios::in);
f.open(m.data(),ios::out);
it will never read the input file. Change to:
std::ifstream in(s.data());
std::ofstream out(m.data());
The while loop is incorrect, the result of a read attempt should be checked immediately after the read:
char ch;
while(in.get(ch))
{
out << ch;
}
cout << "\nFinished!"<< endl; // Moved this to outside the while