What I did here is, read the file char by char. Upon seeing a newline char \n
broke the reading process and written the final word. Until seeing a space kept adding characters to a string named str
. Upon seeing the space, pushed the str
into the vector and cleared the str
to refill it on next loop.
This just keeps repeating until it sees a new line character. At the end I printed vector contents on screen. I've provided example file binStr.txt
that I've used and the output below.
I hope this helps you.
#include <string>
#include <vector>
#include <fstream>
#include <iostream>
int main()
{
std::vector <std::string> words;
std::string str;
std::ifstream stackoverflow("binStr.txt");
char c;
while (stackoverflow.get(c))
{
str += c;
if(c == '\n')
{
words.push_back(str);
str.clear();
break;
}
if(c == ' ')
{
words.push_back(str);
str.clear();
}
}
stackoverflow.close();
for (unsigned int i = 0; i < words.size(); ++i)
std::cout << "Word: " << words[i] << "\n";
return 0;
}
File content:
test some more words until new line
hello yes
maybe stackoverflow potato
Result:
Word: test
Word: some
Word: more
Word: words
Word: until
Word: new
Word: line