I created a very simple code, but the push_back function doesn't want to work. It gives me an absolutely different result than expected.
Here is the code:
std::vector<std::string> words;
std::ifstream infile ("words.txt");
std::string temp;
while (std::getline(infile, temp))
{
words.push_back(temp);
}
for (std::size_t i = 0; i < words.size(); i++)
{
std::cout << words[i] << " ";
}
The "words.txt" file contains only 4 words:
window
tyre
give
speaker
The result is supposed to be "window tyre give speaker", but for me it is " speaker". What is the problem?
1 Answer 1
This proved to be the underlying problem:
Have you tried dumping the input file (e.g. with hexdump -C or similar) to check for rogue control sequences such as \r which might explain the behaviour which you are seeing.
Your input file might be a text file from a DOS/Windows-like system and you might be using a Unix-like system.
hexdump -Cor similar) to check for rogue control sequences such as\rwhich might explain the behaviour which you are seeing. (Your input file might be a text file from a DOS/Windows like system and you might be using a unix-like system.)std::getline(infile, temp,'\r')