Reading from File and store in differernt arrays - c++

I need coding for reading from File and store in differernt arrays !!!
for eg :
paul 23 54
john 32 56
My requirement are as follows: I need to store paul,john in string array and 23,32 in one integer array; and similarly 54,56 in another int array.
I read the inputs from the file and print it but I am unable to save in 3 different arrays.
int main()
{
string name;
int score;
ifstream inFile ;
inFile.open("try.txt");
while(getline(inFile,name))
{
cout<<name<<endl;
}
inFile.close();
}
So kindly suggest me some logics for doin this and I would really appreciate that... !!!

I assume you are new to programming? Or new to C++? So I provided the sample code to get you started. :)
#include <string>;
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> name;
vector<int> veca, vecb;
string n;
int a, b;
ifstream fin("try.txt");
while (fin >> n >> a >> b) {
name.push_back(n);
veca.push_back(a);
vecb.push_back(b);
cout << n << ' ' << a << ' ' << b << endl;
}
fin.close()
return 0;
}

You can try the following code:
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
int main()
{
std::string fileToRead = "file.log";
std::vector<int> column2, column3;
std::vector<std::string> names;
int number1, number2;
std::string strName;
std::fstream fileStream(fileToRead, std::ios::in);
while (fileStream>> strName >> number1 >> number2)
{
names.push_back(strName);
column2.push_back(number1);
column3.push_back(number2);
std::cout << "Value1=" << strName
<< "; Value2=" << number1
<< "; value2=" << number2
<< std::endl;
}
fileStream.close();
return 0;
}
The idea is to read the first column in file to a string (strName) and then push it to a vector (names). Similarly, second and third columns are read into number1 and number2 first and then pushed into vectors named column1 and column2, respectively.
Running it will get you the following results:
Value1=paul; Value2=23; value2=54
Value1=john; Value2=32; value2=56

Related

Create a vector of strings from file c++

I am trying to input three pieces of information from a .txt file.
First column is the course mark.
Second column is the course code.
Third column(s) is the course name.
I would like to store these as 3 vectors of strings.
Would using stringstream be a good option here? and maybe iterators?
The .txt file is like
65.6 10071 Mathematics 1
66.7 10101 Dynamics
60.0 10121 Quantum Physics and Relativity
66.9 10191 Introduction to Astrophysics and Cosmology
... ... ...
and my code so far is
#include<iostream>
#include<iomanip>
#include<fstream>
#include<cmath>
#include<algorithm>
#include<string>
#include<iterator>
#include<sstream>
#include<vector>
//Main Function
int main()
{
//Define variables
std::string course_mark, course_code, course_name;
std::vector<std::string> course_mark_vector;
std::vector<std::string> course_code_vector;
std::vector<std::string> course_name_vector;
std::string data_file[100];
// Ask user to enter filename
std::cout<<"Enter data filename: ";
std::cin>>data_file;
int i{0};
// Open file and check if successful
std::fstream course_stream(data_file);
if(course_stream.is_open()) {
while (!course_stream.eof()) //while the end of file is NOT reached
{
//I have 2
getline(course_stream, course_mark, ' ');
course_mark_vector.push_back(course_mark);
getline(course_stream, course_code, ' ');
course_code_vector.push_back(course_code);
getline(course_stream, course_name, '\n');
course_name_vector.push_back(course_name);
i += 1; //increment number of lines
}
course_stream.close(); //closing the file
std::cout << "Number of entries: " << i-1 << std::endl;
}
else{
std::cout << "Unable to open file. Please run again" << std::endl;
return 1;
}
Any help would be greatly appreciated
Would using stringstream be a good option here?
Yes.
and maybe iterators?
There is no need for iterators in this case.
Try this:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <iomanip>
//Main Function
int main()
{
//Define variables
std::string course_mark, course_code, course_name, data_file, line;
std::vector<std::string> course_mark_vector, course_code_vector, course_name_vector;
int i = 0;
// Ask user to enter filename
std::cout << "Enter data filename: ";
std::cin >> data_file;
// Open file and check if successful
std::ifstream course_stream(data_file);
if (!course_stream.is_open())
{
std::cout << "Unable to open file. Please run again" << std::endl;
return 1;
}
while (std::getline(course_stream, line)) //while the end of file is NOT reached
{
std::istringstream iss(line);
iss >> course_mark;
course_mark_vector.push_back(course_mark);
iss >> course_code;
course_code_vector.push_back(course_code);
std::getline(iss >> std::ws, course_name);
course_name_vector.push_back(course_name);
++i; //increment number of lines
}
course_stream.close(); //closing the file
std::cout << "Number of entries: " << i << std::endl;
return 0;
}
Demo

How to get the average from data.txt file with C++?

Our professor wants us to fix the code which counts the amount of values in a data.txt file and computes their average. Here is the code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
string s;
ifstream f;
int nItems;
double * data;
double sum=0;
vector < double > data2;
double item;
cout <<"File name: ";
cin >> s;
f.open (s.c_str() );
while (! f.eof() )
{
f >> item;
data2.push_back(item);
}
for (int i =0; i < nItems; i++)
{
sum += data[i];
}
cout << "The average is " << sum/nItems <<".\n";
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}
His instructions were:
Modify code worked on today so that the average of data in vector < double > data is computed properly. Right now the code just gives you a value which isn't the average.
I tried changing the nItems variable into 12 and that seemed to work, but the goal of the code is to determine nItems and use that to find the average, which I can't seem to figure out.
You use data for which you haven't allocated any memory when you summarise That causes undefined behaviour. You've stored your values in data2. Remove variables you don't need. Also, using namespace std is considered bad practice.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <numeric> // std::accumulate
int main(int, char**) {
std::string filename;
std::cout << "File name: ";
std::cin >> filename;
std::ifstream f(filename); // no need for .c_str()
std::vector<double> data;
double item;
// instead of checking for eof, check if extraction succeeds:
while(f >> item) {
data.push_back(item);
}
// a standard way to sum all entries in a container:
double sum = std::accumulate(data.begin(), data.end(), 0.);
std::cout << "The sum is " << sum << "\n";
// use the containers size() function. it returns the number of items:
std::cout << "The average is " << (sum / data.size()) << "\n";
}
Hey looks like you weren't reading the numbers in from the txt file.
Here I look through the input file once just to count how many numbers there are
so I can make the array.
Then I look through it again to fill the array.
#include <cstdlib>
#include <iostream>
#include <fstream>
// f here stands for find, fstream gives you files
using namespace std;
int main(int argc, char *argv[]) {
string s;
ifstream f;
// input file stream
int nItems;
double * data;
double sum=0;
cout << "File name: ";
cin >> s;
f.open (s.c_str() );
// s.c_str will return a char array equivalent of the string s
nItems=0;
int input =0;
while (f >> input) {//first loop reading through file to count number of items
nItems++;
}
f.close();
data = new double[nItems]; //Make the array
f.open (s.c_str() );//open file for second read
int i=0;
while (f >> input) {//Second loop through file fills array
data[i] = input;
i++;
}
f.close();
for (int i = 0; i < nItems; i++) {
sum += data[i];
}
cout << "The average is " << sum / nItems << ".\n";
cout << endl;
system("pause");
return 0;
}

I want to calculate total and average of data from text file using C++

I want to calculate total and average of data from text file using C++.
Here is my code and text file.
This code is not showing anything on run
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
using namespace std;
string double2string(double);
double string2double(string);
int main(int argc, char* argv[]){
fstream dfile;
string s1;
string amount;
double damount;
double sum = 0;
dfile.open(argv[1]);
dfile >> amount;
damount = string2double(amount);
while(damount){
sum = sum + damount;
}
string total = double2string(sum);
dfile.clear();
dfile.close();
cout << total;
return 0;
}
Functions to convert string to double and double to string
string double2string(double d){
ostringstream outstr;
outstr << setprecision(2) << fixed << setw(10) << d;
return outstr.str();
};
double string2double(string s1){
istringstream instr(s1);
double n;
instr >> n;
return n;
}
Here is my text file "data.txt"
234
456
789
You need to use a while loop. You're reading in only one line, so you need to make sure that you keep reading in lines until the end of the file.
Also, you might want to use a standard library function: std::stoi is the C++11 and onward version that works for std::string, but std::atoi from <cstdlib> works just as well with std::string.c_str().
#include <iostream>
#include <fstream>
#include <string>
//Compile with C++11; -std=c++11
int main(int argc, char** argv) {
std::fstream file;
//Open the file
file.open(argv[1]);
std::string buffer = "";
int sum = 0;
int n = 0;
//Check for file validity, and keep reading in line by line.
if (file.good()) {
while (file >> buffer) {
n = std::stoi(buffer);
sum += n;
}
std::cout << "Sum: " << sum << std::endl;
} else {
std::cout << "File: " << argv[1] << "is not valid." << std::endl;
}
return 0;
}

Using getline to read data from a file in C++

I want to read from a file two things, the full name (first name and last name)
and age. After that I want to store them in an array then print the data.
However, when I try to reading the first record is read find, but the other two are not.
Please tell me what am I missing.
Thank you.
The content of the file is:
sampleFirst1 sampleLast1
30
sampleFirst2 sampleLast2
25
sampleFirst3 sampleLast3
40
The Output is:
Name: sampleFirst1 Age: 30
Name: Age: 30
Name: Age: 30
Here's my Code:
#include "Person.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile("data.txt", ios::in);
string full_name;
int age = 0;
int i = 0;
Person personArray[3];
while (i < 3)
{
getline(inputFile, full_name);
personArray[i].set_name(full_name);
inputFile >> age;
personArray[i].set_age(age);
++i;
}
inputFile.close();
printData(personArray, 3);
cout << endl;
return 0;
}
You should not mix getline and the >> operator in that way. Prefer a simpler code like this one :
#include <iostream>
#include <fstream>
#include <array>
#include <string>
using namespace std;
struct Person {
std::string name;
int age;
void set_name(std::string const& i_name) { name = i_name; }
void set_age(int i_age) { age = i_age; }
};
int main()
{
ifstream inputFile("data.txt", ios::in);
std::string first;
std::string last;
int age = 0;
int i = 0;
std::array<Person,3> personArray;
while (i < personArray.size()) {
inputFile >> first >> last >> age;
personArray[i].set_name(first + " " + last);
personArray[i].set_age(age);
++i;
}
inputFile.close();
for(Person const& person : personArray) {
std::cout << "Name: " << person.name << " Age: " << person.age << "\n";
}
std::cout << std::flush;
return 0;
}
Or use only getline and a istringstream to pase the age if you dont want to pay the string concatenation extra cost for the full name.
A lot could be said of the parsing method but that is not the point here.

Reading information into array of structs c++

I'm making a program for my c++ class. Ultimately I want my program to perform a quicksort on a text file of contacts in the following format:
Firstname Secondname Number
Each contact is separated by a new line. I've started by counting the number of lines and using dynamic memory allocation to create an array of structs which has the same size as the number of lines.
However, when I tried to read in the information from the text file and output it to the screen, all I get is gibberish. I've had a look around on the internet to try and find a solution but everything I've found seems to use a different syntax to me.
Here's my code so far:
#include <iostream>
#include <fstream>
#include <istream>
char in[20];
char out[20];
using namespace std;
struct contact
{
char firstName[14];
char surName[14];
char number[9];
};
//structure definition
int main(void){
cout << "Please enter the input filename: " << endl;
cin >> in;
ifstream input(in);
if(!input){
cerr << "failed to open input file " << in << endl;
exit(1);
}
cout << "Please enter tne output filename: " << endl;
cin >> out;
// read in the input and output filenames
char a;
int b=0;
while (input.good ())
{
a=input.get ();
if (a=='\n')
{
b++;
}
}
// count the number of lines in the input file
input.seekg (0, ios::beg);
//rewind to beginning of file
contact* list = new contact[b];
//dynamically create memory space for array of contacts
int i = 0.;
while(input){
if(i >= b) break;
if(input >> *list[i].firstName >> *list[i].surName >> *list[i].number) i++;
else break;
}
input.close();
//read information from input file into array of contacts
for(int N = 0; N < b; N++){
cout << list[N].firstName << list[N].surName << list[N].number << endl;
}
ofstream output(out);
int k = 0;
for(int k = 0; k<b; k++){
output << list[k].firstName << " " << list[k].surName << " " << list[k].number << endl;
}
//print out the unsorted list to screen and write to output file
//i've done both here just to check, won't print to screen in final version
output.close();
delete []list;
} // end of main()
You reset the files location to the beginning, but the files eofbit is still labeled as true from when you first read the amount of lines. A quick fix to this is re-opening the file after you read the lines, possibly making the line count a function to clean up code.
int lines(const string path)
{
ifstream tmp(path.c_str());
string temp;
int count = 0;
getline(inFile,temp);
while(inFile)
{
count++;
getline(inFile,temp);
}
tmp.close();
return count;
}
Okay, I put together a quick and dirty method using newer C++ constructs to get you most of the way there. You're on your own for writing to the file (trivial) and the quicksort, though I've put the struct into a vector for you, so sorting the vector is as easy as writing a custom function to compare one struct vs the other. I apologize in advance if some of the code is less than canonical C++. I'm way past my bed time, and way tired, but this was interesting enough of a problem that I wanted to give it a go. Happy coding!
#include <iostream>
#include <fstream>
#include <istream>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>
#include <sstream>
using namespace std;
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
return split(s, delim, elems);
}
struct contact
{
std::string firstName;
std::string surName;
std::string number;
contact(std::string& fName, std::string& lName, std::string& num) : firstName(fName), surName(lName), number(num) {}
};
//structure definition
char in[20];
char out[20];
int main()
{
std::vector<contact> contacts;
cout << "Please enter the input filename: " << endl;
cin >> in;
ifstream input(in);
if(!input){
cerr << "failed to open input file " << in << endl;
exit(1);
}
cout << "Please enter tne output filename: " << endl;
cin >> out;
std::string sinput;
// read in the input and output filenames
while (input.good ())
{
getline(input, sinput);
vector<string> tokens = split(sinput, ' ');
if (tokens.size() == 3)
{
contact c(tokens[0], tokens[1], tokens[2]);
contacts.push_back(c);
}
}
input.close();
//read information from input file into array of contacts
std::cout << "Outputting from vector..." << std::endl;
for_each(contacts.begin(), contacts.end(), [](contact& c) {
cout << c.firstName << " " << c.surName << " " << c.number << endl;
});
return 0;
}
Also, just want to give credit that the split methods come from this answer on this very site. Cheers!