B
BigMan
How does one rewrite the following piece of code using std::cin?
int n;
scanf( "n=%d", &n );
int n;
scanf( "n=%d", &n );
BigMan said:How does one rewrite the following piece of code using std::cin?
int n;
scanf( "n=%d", &n );
Evan said:Depends on how closely you want the behavior to match. This is as
close to the behavior as I can get:
char prefix[2];
cin.get(&prefix[0], 3);
Hey man! IGNORE THE PREVIOUS POST (mad) !!!!! IT actually SUCKs forBigMan said:How does one rewrite the following piece of code using std::cin?
int n;
scanf( "n=%d", &n );
Evan said:Ah, it's a serious mistake. Though actually it's the 2 that is the
dimensions of the prefix array that is wrong, not the 3 in get.
I didn't think about the null termination character that get adds at
the end and only gave space for the 'n' and '=' characters.
Turning on
MSVC's stack frame checking showed that the get call was stomping over
other parts of the stack; changing the dimension to 3 fixed it.
Corrected code is as follows:
char prefix[3];
cin.get(&prefix[0], 3);
Thanks for the correction.
(You know, when my subconscious goes "that's not right -- why are the
numbers different", I really ought to look into it more...)
input stream. If you read 3, a subsequent read will be missing the leading
digit. I am too lazy to check now, but RTFM on istream::get.
Evan said:Actually I still think you should be only reading 2 characters from
the input stream. If you read 3, a subsequent read will be missing
the leading digit. I am too lazy to check now, but RTFM on
istream::get.
get( buffer, count ) reads count-1 characters from the string, then
tags on a terminating 0.
"The three-argument s.get(p,n,term) reads at most n-1 characters into
p[0]..p[n-2]. A call of get() will always place a 0 at the end of the
characters (if any) it placed in p[], so p must point to an array of
at least n characters." (3rd edition of Strostrup, p. 618-619)
cin.read is available if you don't want the null termination added.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.