I'm extracting some data from a text file and put them in 2 vectors but the output of std::getline() is not as I expected. Here's the code:
std::vector<std::string> v1;
std::vector<std::string> v2;
const char* filename = "words.txt";
std::ifstream fin(filename);
if (!fin) {
throw "Bad file name!";
}
else {
// File is good
std::string temp;
while (std::getline(fin, temp)) {
std::cout << "(((Temp: " << temp << ")))" << std::endl;
v1.push_back(temp.substr(0, temp.find(' ')));
// Erase first character
temp.erase(0, temp.find(' ') + 1);
// Erase spaces
v2.push_back(temp.substr(temp.find_first_not_of(' '),temp.find_last_not_of(' ') - temp.find_first_not_of(' ') + 1));
}
}
// output v1:
std::cout << "\nValues of v1:\n";
for (auto word : v1){
std::cout << "(((" << word << ")))" << std::endl;
}
// output v2:
std::cout << "\nValues of v2:\n";
for (auto word : v2){
std::cout << "(((" << word << ")))" << std::endl;
}
Here's the "words.txt":
a A
b B
c C
d D
e E
The real words.txt is more complicated but similar.
And here's the output:
)))Temp: a A
)))Temp: b B
)))Temp: c C
)))Temp: d D
)))Temp: e E
Values of v1:
(((a)))
(((b)))
(((c)))
(((d)))
(((e)))
Values of v2:
)))A
)))B
)))C
)))D
)))E
Why is there a difference in the output from each line read from the file and between the 2 vectors?