jalkadir wrote:
>
> By jump I mean ending unexpectedly.
> The program below, like the jumping beens, has an unusual behaviour.
> When the noted lines are not present the program terminates
> disregarding the rest of the lines.
>
> I have seen this type of behaviour before, but I can't find to recall
> the source, the needy greedy source, of the problem. I, however, was
> able to remember that the problem was resolved, temporarily, by using
> 'std::cin.get()', but I am afraid this will lead to a bug in the
> future.
>
> Can anyone help me by explaining what causes this type of behaviour,
> why my solution works and, most importantly, how to solve the problem.
>
> Thanks in advance
>
> ---
> void getData(){
> jme::Address address2;
> std::string str;
> char* cstr;
> std::cout.flush();
> //std::cin.get().flush();
>
> str.clear();
> std::cout << "House/Appartment # ";
> std::cin >> str;
> std::cin.get(); // Without this line the program jumps <====
Whatever 'jump' means.
I guess you mean, the next input seems to be ignored.
Well that is easy to explain: When you enter some number, what *exactly*
do you enter? You press eg. the keys '1', then '3' (because you want to
enter the number 13) and then? Then you press 'return'. And that 'return'
is still waiting to be processed after cin >> str has fetched the '1' and '3'.
That is why you intoduced the read of a single character: To read that 'return'
still waiting for input. If you don't do it now, then the next get will grab
his hands on that waiting 'return' and conclude that the user made an empty input.
> address2.setUnitNumber(str);
>
> std::cout << "Enter street name: ";
> std::cin.get(cstr,255);
Ouuuh. That is a big no-no.
cstr is a pointer. But a pointer to where? Where is the memory
where get() should put the characters and whos address you take
from cstr?
Answer: There is none! cstr is an uninitialized pointer and only god
knows where it points to in memory. Why didn't you use the variable 'str'
as you did above to get a string from the user?
--
Karl Heinz Buchegger