Click here to Skip to main content
15,889,808 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, I've created a txt file (c++ language) and then try to copy his element in a vector so that each element of the vector is a line of the file. But at the end when i try to display the elements of the vector, there are voids elements but i don't know how to remove them.

What I have tried:

C++
ifstream sjp2("L2.txt");
while(getline(sjp2,s))
L2.push_back(s);
Posted
Updated 2-Sep-22 1:29am
Comments
CPallini 1-Sep-22 14:04pm    
Your code looks correct. However, without knowing the exact input data, it is difficult to give help.
Richard MacCutchan 1-Sep-22 14:11pm    
Check that each line actually contains some text before you add it to the vector.

(I originally submitted this as a comment in Solution 1, but it wouldn't format properly.)

The easiest way to avoid empty strings in the vector is not to put them there in the first place:
C++
while(getline(sjp2,s))
{
   if(!s.empty() && (s.back() == '\r')) s.pop_back();
   if(!s.empty()) L2.push_back(s);
}
That pop_back line is in case the file you're reading was created on Windows but is being read on Linux. Windows adds "\r\n" at the end of a line, whereas Linux only adds '\n'. It is therefore necessary to strip out the '\r'. You can remove that line unless you need to handle that scenario.
 
Share this answer
 
v3
Comments
Shalom Kamokoue 2-Sep-22 10:08am    
Thank you very much!
You have not shown what type the variables L2 or s are so I will guess s is of type std::string and L2 is a std::vector< std::string >. With those guesses, your code appears to be correct. To write there are "voids" elements makes no sense - what does "voids" mean? You might have empty strings in vector but that is likely to be because of empty lines in the text file. Again, I can only guess because I can't see the text file or what your output looks like. YOU need to make that comparison and see if it makes sense.

With a bit more information I could probably be more helpful.
 
Share this answer
 
Comments
Shalom Kamokoue 2-Sep-22 4:54am    
Thank you very much for your answer. There might have been empty strings in vector. Do you know a way to remove these empty strings without modifying the file? (In the file there are no empty lines so I don't know what to do)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900