"New Line" connected to value when reading in a CSV? [duplicate] - c++

This question already has answers here:
How can I read and parse CSV files in C++?
(39 answers)
Closed 6 years ago.
I am currently trying to read in a CSV file to place it into an array, but when I execute the code, the program seems to read over the endline to the next comma which messes up my output. Here is the code:
while (!inFile.eof()) {
string line = "";
while (count_1 <= numValuesPerLine) {
getline(inFile, readFromFile, ',');
line.append(readFromFile);
count_1++;
}
cout << line << endl;
count_1 = 0;
}
'line' ends up having the value:
12345678910111213141516171819202122232425\n1
which when I print it, places that newline next to '25' and messes up the output.
(numValuesPerLine = 25 and count_1 is initialized outside of the loop)
I looked around for a similar answer but I could not find anything exactly like what I am trying to do, any help would be greatly appreciated, thank you.

you changed the delimiter from \n to , so of course the newline is kept as part of the input

Related

C++ how to read a line with delimiter until the end of each line? [duplicate]

This question already has answers here:
How can I read and parse CSV files in C++?
(39 answers)
Closed 6 years ago.
Hi I need to read a file that looks like this...
1|Toy Story (1995)|Animation|Children's|Comedy
2|Jumanji (1995)|Adventure|Children's|Fantasy
3|Grumpier Old Men (1995)|Comedy|Romance
4|Waiting to Exhale (1995)|Comedy|Drama
5|Father of the Bride Part II (1995)|Comedy
6|Heat (1995)|Action|Crime|Thriller
7|Sabrina (1995)|Comedy|Romance
8|Tom and Huck (1995)|Adventure|Children's
9|Sudden Death (1995)|Action
As you can see the type of each movie can vary from 1 type to many...I wonder how could I read those until the end of each line?
I'm currently doing:
void readingenre(string filename,int **g)
{
ifstream myfile(filename);
cout << "reading file "+filename << endl;
if(myfile.is_open())
{
string item;
string name;
string type;
while(!myfile.eof())
{
getline(myfile,item,'|');
//cout <<item<< "\t";
getline(myfile,name,'|');
while(getline(myfile,type,'|'))
{
cout<<type<<endl;
}
getline(myfile,type,'\n');
}
myfile.close();
cout << "reading genre file finished" <<endl;
}
}
the result is not what I want...It looks like:
Animation
Children's
Comedy
2
Jumanji (1995)
Adventure
Children's
Fantasy
3
Grumpier Old Men (1995)
Comedy
Romance
So it doesn't stop at the end of each line...How could I fix this?
Attempting to parse this input file one field at a time is the wrong approach.
This is a text file. A text file consists of lines terminated by newline characters. getline() by itself, is what you use to read a text file, with newline-terminated lines:
while (std::getline(myfile, line))
And not:
while(!myfile.eof())
which is always a bug.
So now you have a loop that reads each line of text. A std::istringstream can be constructed inside the loop, containing the line just read:
std::istringstream iline(line);
and then you can use std::getline(), with this std::istringstream with the optional delimiter character overriden to '|' to read each field in the line.

Problems with reading text from a file [duplicate]

This question already has answers here:
Read whole ASCII file into C++ std::string [duplicate]
(9 answers)
Closed 9 years ago.
I have this function that reads the text from a file and adds it to a string, now the weird thing is that it works fine if its a short text. But if its a longer text the string becomes empty, any help solving this problem is appreciated.
string inlasning(string namn)
{
string filString, temp;
ifstream filen(namn.c_str());
if(!filen.good())
{
cout << "Otillganglig fil" << endl;
filString = "ERROR";
return filString;
}
else
{
while(!filen.eof())
getline(filen, temp);
filString.append(temp);
}
filen.close();
return filString;
}
1) Don't use eof() to control the loop. Put getline directly into the loop condition. Search StackOverflow if you have problems doing this.
2) Your while loop has no braces and thus only covers the getline line, despite your misleading indentation.
3) getline discards newlines. Your final string will be wrong.
4) The actual behavior you're observing comes from the fact that you only append the very last thing that getline returns to your string. When your file contains one line of text and doesn't end in a newline, this will seem to work. If it has more lines but doesn't end in a newline, you'll only get the last line. If the file does end in a newline, because of your incorrect loop condition the last call to getline will actually give you an empty string, which will be exactly the contents of your string.
Replace
while(!filen.eof())
getline(filen, temp);
filString.append(temp);
with
while(!filen.eof())
{
getline(filen, temp);
filString.append(temp);
}
Use "is_open()" to check if the file exists:
if( ! filen.is_open() ){...} // you don't need an else clause
...And your while loop must has braces or it will only execute the getline(...) instruction:
while( filen.good() ) {
getline( filen , temp );
filString += ( temp + '\n' );
}
If your file doesn't ends with '\n', remove the last char from the string

reading from file to vector- last line gets repeated [duplicate]

This question already has answers here:
Reading from text file until EOF repeats last line [duplicate]
(7 answers)
Testing stream.good() or !stream.eof() reads last line twice [duplicate]
(3 answers)
reading a line in text file twice
(4 answers)
Closed 9 years ago.
I am trying to read values from a file to a vector
std::vector<float> setTimesArray (std::string flName){
int i=0, dummy=0;
float temp;
std::vector<float> pObs;
std::string line;
std::ifstream inFile;
inFile.open(flName.c_str());
if(!inFile){
std::cout<<"\n.obs file not valid. Quitting programme...";
exit(1);
}
while(inFile.good()){
i++;
getline(inFile, line);
if(i>=3){ //I don't want first two lines
std::istringstream in(line);
in>>dummy;//discards first value in the line
in>>temp;
pObs.push_back(temp);
in.str(""); //discards remaining part of the line
}
}
return pObs;
inFile.close();
}
Problem is, the last value gets repeated. For example, flName had total 975 lines. Thus pObs must be having size=973 (975-2 initial lines). But the size is 974 and I see that the last value is repeating. What mistake have I made?
try:
while (getline(inFile,line))
instead of while(inFile.good())
and remove the getline() call from within the method.
You may also want to change your last two lines of codes to this, as per Daniel Kamil Kozar's suggestion:
inFile.close();
return pObs;
After the last line, good() is still allowed to return true. It doesn't have to return false until after a failed read. Thus, if it returns true, and then fails the read, your line variable won't take a new value. The correct solution would probably be to correct the bounds checking, but in this case, moving the declaration of line into the scope of you while loop and checking for and empty string should correct the issue.

Is `eof`` a valid state of `ifstream`? [duplicate]

This question already has answers here:
What's preferred pattern for reading lines from a file in C++?
(5 answers)
Closed 9 years ago.
The code is:
ifstream fin("D://abc.txt", ios::in);
string line;
while ( fin ) {
getline( fin, line );
cout << line << endl;
}
The text file is:
hi, I am Eric!
hi, I am Jack!
And the output is
hi, I am Eric!
hi, I am Jack!
hi, I am Jack!
And when I change the condition to !fin.eof(), output is correct. Is eof a valid state of ifstream ?
It's because the state is not changed until after the std::getline function fails. This means that you read the first two lines correctly, but then the state isn't changed so you enter the loop again, but now the std::getline call fails but you don't check for it, and it's also now that the eof flag is set.
You should do e.g.
while (std::getline(...))
{
// ...
}
The eof state is only reached once you try reading past the end of the stream. The getline call that reads the last line from your file does not do so (it reads up until the newline). But the getline call in the next iteration of the loop will reach the end of the file.
A better way to read every line in the file is :
while (getline(fin, line)) {
cout << line << endl;
}
The usage
while(fin)
is not good. it will check the value of fin, not whether fin reaches the end.
you may check this page:
http://www.cplusplus.com/reference/string/string/getline/
when you finish the second call of function getline, the pointer fin not point to NULL, so you go into the third process in while, the third time you call
getline(fin,line);
it meet the eof of fin, so fin change state, then you won't go to the forth call, but since you didn't clear the value of
line
so it will also print
hi, I am Jack!

Reading delimited files in C++ [duplicate]

This question already has answers here:
How can I read and parse CSV files in C++?
(39 answers)
Closed 8 years ago.
What is the best way to read in a tab delimited file in C++ and store each line as a record? I have been looking for an open source library to help with this, but have been unsuccessful so it looks like I will have to write my own.
typedef vector<vector<string> > Rows;
Rows rows;
ifstream input("filename.csv");
char const row_delim = '\n';
char const field_delim = '\t';
for (string row; getline(input, row, row_delim); ) {
rows.push_back(Rows::value_type());
istringstream ss(row);
for (string field; getline(ss, field, field_delim); ) {
rows.back().push_back(field);
}
}
This will get you started. It doesn't do any checking that each row has the same number of fields, allow for escaping field_delim, etc.
There is no problem in using iostreams - you could read each line with getline into string, and then use stringstream on that string to iterate over fields.
There are a few libraries listed in wikipedia's article CSV_application_support.