C++ Reading text file, storing objects and printing out array [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm reading in an input file with tab delimited Firstname, Lastname and zipcode. There are 25 of them. I'm trying to read it in, store it into objects and print it out again.
Here's the code:
// Reading in from an input file
ifstream inputFile("nameInput.txt");
string line;
for(int i = 0; i<25; i++){
while (getline(inputFile, line))
{
istringstream getInput(line);
string tempFName, tempLName;
int tempZip;
getInput >> tempFName >> tempLName >> tempZip;
// Creating new Person objects with the data
persons[i] = new Person(tempFName, tempLName, tempZip);
}
inputFile.close();
// Printing out String representation of the Person
persons[i]->toString();
}
While it compiles, during run-time this is the error I get: 87023
Segmentation fault: 11
Please help!!

The thing is, you need only one loop. This will read a maximum of 25 lines:
int main()
{
const int n_persons = 25;
std::shared_ptr<Person> persons[n_persons];
std::ifstream inputFile("nameInput.txt");
std::string line;
for(int i = 0; i < n_persons && std::getline(inputFile, line); ++i)
{
std::istringstream getInput(line);
std::string tempFName, tempLName;
int tempZip;
if(getInput >> tempFName >> tempLName >> tempZip)
{
// Creating new Person objects with the data
persons[i] = new Person(tempFName, tempLName, tempZip);
// Printing out string representation of the Person
persons[i]->toString();
}
else
cout << "error on line #" << i + 1 << " occurred" << endl;
}
}

Related

Reading Different Variable types from one File c++ [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 2 years ago.
I am having a bit of trouble on reading data in a specific format into different variables. I need to read the data from the file and store into 5 different variables of different variable types.(string Name, string Fish, string Location, float Length, float Weight)
The format of the Data I am trying to store is as follows:
Picture of How Data is Stored in File
I have no issues obtaining the name, fish, and location from the file using the getline() function. My issue comes with the length and width.
ifstream file("test.txt");
while(file.good())
{
getline(file, Name);
getline(file, Species);
getline(file, Location);
file >> Length;
file >> Weight;
cout << Name << "\n" << Species << "\n" <<Location << "\n" <<Length << "\n";
}
When I use the following code the output becomes wonky and it prints the data out of order after the first listing. Any help with this would be greatly appreciated.
ifstream file("test.txt");
while (file) {
getline(file, Name);
getline(file, Species);
getline(file, Location);
file >> Length;
file >> Weight;
if (file) {
cout << Name << "\n" << Species << "\n" <<Location << "\n" <<Length << "\n";
// add this to skip the 2 newlines before reading the next string
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
else {
throw "Invalid input";
}
}

How to assign words from csv assign to variables? [duplicate]

This question already has answers here:
How can I read and parse CSV files in C++?
(39 answers)
Closed 2 years ago.
I have a code that reads a file with a following:
word1,word2,word,3....,word8
word1,word2,word,3....,word8
word1,word2,word,3....,word8
ifstream infile;
//string path;s
infile.open("file.csv");
string line;
CourseNode *current = head;
int i=1;
if(infile.is_open()){
while(getline(infile, line)) {
if(i == 1)
cout << "1st line==> "+line << endl; // ignore first line
else { // read data
string firstname, lastname, id, a,b,c,d,t ;
stringstream sst(line);
getline(getline (sst, firstname, ','),lastname, ',');
//getline(getline(getline (sst, firstname, ','),lastname, ','),id, ',');
cout << "result==> "<< firstname<<" "<<lastname << endl;
}
i++;
}
I assume i have to work with this line and insert there my string variables but i am not sure how!
getline(getline (sst, firstname, ','),lastname, ',');
Any help will be appreciateed! Thank you!
To read a .csv file you may read the entire line and split after to load easly your data:
std::ifstream infile;
infile.open("file.csv");
std::string line;
int i = 1;
if(infile.is_open()){
while(getline(infile, line)) {
if(i == 1) {
// ignore line
continue;
} else { // read data
std::vector<std::string> value; // this is where you stock the data
value = split(line); // add your implementation of split
// here: do something with the data in value
}
i++;
}
}
You have in value every data from a line of your .cvs file. Now, you can assigne every case to a specific variable or put them in a list of object.

i want to read the file and write destinations into the destination array and prices into the price array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have written a file with 4 holiday destination and there prices , so i want to read the file and write destinations into the destination array and prices into the price array. the text format is like
suncity 250
ushakamarue 300
krugerPark 450
Tablemountain 340
this is what i have
#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>
using namespace std;
//define a constant for the number of lines to read
#define NUM_READ_LINES 4
int main()
{
// array of line numbers each line being less or equal to 100 chars
char destination[NUM_READ_LINES][100];
//string price[30];
int counter = 0;
//ofstream outfile;
ofstream outfile("program.txt");
if(outfile.is_open())
{
outfile <<"suncity 250\n ";
outfile <<" ushakamarue 300\n";
outfile <<" krugerPark 450\n";
outfile <<" Tablemountain 340\n";
}
else
cout <<"Unable to open to file";
outfile.close();
//open a file
ifstream infile;
infile.open("program.txt");
if(infile.good())
{
//Read throuh file and load into array
while(!infile.eof() && (counter < NUM_READ_LINES))
{
infile.getline(destination[counter], 100);
counter++;
}
//loop hrough the array which we just put together
for (int i=0; i < counter;i++ )
{
cout << destination[i]<<endl;
}
}
infile.close();
return 0;
}
Currently the program is reading the whole line suncity 250 as destination instead of reading only suncity into destination[1] and 250 into Price[1].
Something like this:
string destination[NUM_READ_LINES];
string price[NUM_READ_LINES];
ifstream infile("program.txt");
for (int ii = 0; ii < NUM_READ_LINES; ++ii) {
infile >> destination[ii] >> price[ii];
}

how to make variables out of a string in c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
this is my code below, the output is numbers relating to a grade. I want to be able to make each line of the string a variable such as int grade1 and so on, so that I can display certain variables and not the whole string for example cout << grade1 << grade2 << endl;
using namespace std;
int main()
{
string line;
ifstream myfile("Data.csv"); //opening the CVS file
if (myfile.is_open())
{
while (getline(myfile, line)) //used to read each line of the file
{
string str(line); //making the file a string
char chars[] = ",abcdefghijklmnopqrstuvwxyzN;:/"; //Characters to be removed
for (unsigned int i = 0; i < strlen(chars); ++i)
{
str.erase(std::remove(str.begin(), str.end(), chars[i]), str.end());
}
str.replace(0, 9, " ");
cout << str << endl;
}
myfile.close(); //closes the file
}
else
cout << "pathway to file can't be found" << '\n'; //error message to display if file location cant be found.
cin.get();
return 0;
}
The question and especially the code is rather difficult to comprehend, but I understood that you want to create string variables for each line of the file.
A simple way is to loop through the file line-by-line, store the line into a string variable and then push that variable to a vector.
std::string line;
std::vector<std::string> lines;
while (getline(myfile, line))
{
lines.push_back(line);
}

C++ Read txt file CSV values

I know this post has been made before on stack overflow, and I have combined various tutorials; but why does this code cause an error on execution - it does compile.
void leaderBoard::loadFromFile(void)
{
string line;
ifstream leaderBoardFile ("leaderboard.data");
vector<string> playerInfoVector;
if (leaderBoardFile.is_open())
{
while ( leaderBoardFile.good() )
{
playerInfoVector.clear();
getline (leaderBoardFile,line);
std::string input = line;
std::istringstream ss(input);
std::string token;
//cout << line << endl;
while(getline(ss, token, ',')) {
//for current line;
playerInfoVector.push_back(token);
}
string firstName = playerInfoVector.at(0);
string stringAge = playerInfoVector.at(1);
string stringScore = playerInfoVector.at(2);
//int age;
//stringstream(stringAge) >> age;
//int score;
//stringstream(stringScore) >> score;
//addScore(firstName,age,score);
////stringstream(stringAge) >> age;
////Add text to vector (push back)
playerInfoVector.clear();
}
leaderBoardFile.close();
}
else cout << "Unable to open file";
}
Yes loads of times
while ( leaderBoardFile.good() )
{
playerInfoVector.clear();
getline (leaderBoardFile,line);
should be
while ( getline (leaderBoardFile,line) )
{
playerInfoVector.clear();
It is incredible how many times this error is repeated. You actually got it right in your second while loop, so why wrong in the first one?
Unfortunately some tutorials also get this wrong.
It would also be sensible to add a check that you really do have three items in your vector. Something like this
if (playerInfoVector.size() < 3)
{
cerr << "Not enough items in player info vector\n";
exit(1);
}
string firstName = playerInfoVector.at(0);
string stringAge = playerInfoVector.at(1);
string stringScore = playerInfoVector.at(2);