Click to See Complete Forum and Search --> : Functions


amarwhey
February 25th, 2006, 09:44 AM
Hi ive written the following bit of code BUT on execution it seems to jump from line 4 all the way to line 9, without accepting user input. The function to be called is also shown. If however i replace line 5 with a cin>>, it works, but i need to be able to read a whole line not just one string, any ideas???



1: cout <<"Please type the verb in your sentance: "<< endl;

2: cin >> verbStr;

3 verbOutStream << verbStr << endl;


4: cout <<"What should the response be?: ";

5: useFunc.readLines( cin, telMe );


6: nounVerbStr = nounStr + space + verbStr;


7: phraseOutStream << nounVerbStr <<endl;
8: phraseOutStream << telMe << endl;


9: cout <<"Phrase added";

10: }
11: else
12: {

13: cout << phrasePair[nounVerbStr];

14: }

15: }



The function im trying to call:



void BOT::readLines( istream & in, string & s )
{// a function to replace getLine() because there was a bug in Visual Studio C++ 6 and you don't know whether
// the patch was applied.
char c;

s.erase(); // clear the old string


c = in.get(); // read one character ahead
while ( c!='\n' )
{// not end of line
s = s + c; // add the string
c = in.get(); // read the next character
}
}






The output:

What should the response be?Phrase added

It should be:
What should the response be? <accept user input "Yes i am fine\n">
Phrase added


Hope som1 can help!!!!!
thanks in advance!!!

Amar!!

SuperKoko
February 25th, 2006, 11:42 AM
That is because of the verbStr input.
cin>>verbStr will input all characters up to any delimiter (space, tab, eof, or newline).
It does not remove the delimiter from the buffer.
So, the first character that the readLines function extract is that '\n' character.

From the user view-point, he must not use a '\n' as delimiter after verbStr
It means that he must do something like:

NewVerb Yes i am fine

And not:

NewVerb
Yes i am fine


To correct that behaviour, simply use readLines for the verbStr input, instead of cin>>verbStr.

Note : readLine is a better name than readLines (it reads only one line).
Your readLine function is not perfect, because it does not test for EOF or any failure.

You should stop reading the string on EOF or hardware failure.
For example, something such as

while(in.get(c) && c!='\n') s+=c;

may be used.

Also, I suggest you use code tags for next messages!

Code should be delimited between and tags.

amarwhey
February 25th, 2006, 01:20 PM
thank you so much mate!!
worked a treat
thanks for the tips also !!
thanks again