|
-
February 25th, 2006, 10:44 AM
#1
Functions
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!!
-
February 25th, 2006, 12:42 PM
#2
Re: Functions
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:
Code:
NewVerb Yes i am fine
And not:
Code:
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
Code:
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 [code] and [/code] tags.
"inherit to be reused by code that uses the base class, not to reuse base class code", Sutter and Alexandrescu, C++ Coding Standards.
Club of lovers of the C++ typecasts cute syntax: Only recorded member.
Out of memory happens! Handle it properly!
Say no to g_new()!
-
February 25th, 2006, 02:20 PM
#3
Re: Functions
thank you so much mate!!
worked a treat
thanks for the tips also !!
thanks again
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|