Text file has an unexpected carriage return

Hi guys,

I have a small data file named Itemdata.dat. It is as follows:

dagger}
a dagger}
1 1 1
torch}
a torch}
2 1 7
glowstone}
a glowstone}
3 1 11
ration of food}
a single ration of food}
4 1 7
rue potion}
a rue potion}
5 2 11


In my program, I use this function to read the file, and push it back into a vector:

1
2
3
4
5
6
7
8
9
10
if (thefile.is_open()){
        while (thefile.good()){
            getline(thefile,name,'}');
            getline(thefile,desc,'}');
            thefile >> id >> weight >> loc;
            Item newobject(name, desc, id, weight, loc);
            std :: cout << "Pushing back " << newobject.getDesc() << std :: endl;
            object.push_back(newobject);
      }
      }


It works fine, except when I get to the cout statement. The out put drops a line before printing newobject.getDesc().
So my output looks like:

Pushing back
A dagger
Pushing back
A torch
Pushing back
A glowstone


My questions ares what’s up with the line feed, and more importantly, how do I get it to print on the same line?
Last edited on
What happen if you output desc ?
Same results.
Not sure but, I think its similar to a problem when mixing cin and getline
See:

http://en.cppreference.com/w/cpp/string/basic_string/getline

When used immediately after whitespace-delimited input, e.g. after int n; std::cin >> n;, getline consumes the endline character left on the input stream by operator>>, and returns immediately. A common solution is to ignore all leftover characters on the line of input with cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); before switching to line-oriented input.
After using >> ignore(...)

You have that problem the second time onward.
The problem is hta your file looks like that (notice newline symbols):
"dagger}\na dagger}\n1 1 1\ntorch}\na torch}\n2 1 7"
Wheny you do getline(thefile,name,'}');, it reads every single character including newlines until it encounters }. YOu need to skip extra newlines, or remove those '}' and read up to newline. In second case you will need to apply coder777 suggestion only once in your loop (as opposed to after every input operation).
Topic archived. No new replies allowed.