0

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?

asked Oct 6, 2013 at 14:14
7
  • Are you sure you're reading correct file ? Commented Oct 6, 2013 at 14:17
  • 4
    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.) Commented Oct 6, 2013 at 14:18
  • yes, i'm. I tried to edit it, but I always get the last word. Commented Oct 6, 2013 at 14:19
  • 2
    Check with std::getline(infile, temp,'\r') Commented Oct 6, 2013 at 14:20
  • 2
    thank you very much :) the '\r' caused the problem. Commented Oct 6, 2013 at 14:29

1 Answer 1

2

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.

answered Oct 6, 2013 at 14:40
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.