Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

new programmer and cin confusion 1

Status
Not open for further replies.

iam3

Programmer
Oct 30, 2001
6
NO
#include <iostream>

main() {
int a = 0;
static char buffer[20] = &quot;hello&quot;;
cout << &quot;Enter [uid] [command]: &quot;;
cin >> a >> buffer;
cout << &quot;Okay, executing &quot; << buffer << &quot; as user &quot; << a << endl;
}

When I run this program with the input &quot;ls100&quot; then it prints

&quot;Okay, executing as user user 0&quot;.
but almost a same program in C writes

&quot;Okay, executing hello as user 0&quot;

Why doesn't C++ do the same? I mean why it doesn't print &quot;hello&quot;, the
initial value......scanf does (C)?
 
i would change that code to do

cin>>a;
cin>>buffer;

you are not sending any input into a (unless you didnt mention you were giving 2 inputs. )

When you try again you will have to enter the number and then enter the buffer or do something like

&quot;10 hello&quot;

Matt
 
ls100, shouldn't that be &quot;100 ls&quot; ?

remark: if you create a buffer, you should clean it first, because they are filled with garbage.

for(int i=0;i<20;i++)buffer=0;

remark: When you use cin,always be aware that it leaves the
enter key in the buffer until you get it out.

if you want to be sure, you can do it this way:

cin>>a; // 100
cin.get(); //remove the enter sign
//if you don't do this, buffer will contain this
// enter sign and the cin will stop!
cin>>buffer;// put &quot;ls&quot; in buffer
cin.get();//remove second enter

hope this helps...
The Muppeteer.



Don't eat yellow snow...
 
You have probably already solved this but it looks like you are assigning the value &quot;hello&quot; to buffer and then trying to reassign some value to buffer from cin. If you didn't say..
cin>>a>>buffer;
but instead said..
cin>>a;
then buffer would retain it's initial value &quot;hello&quot;, and then when you print the output it would print &quot;hello&quot;.
Also it looks like a isn't getting the proper value! If you input ls100, a will not retain a value because it is declared to be an int!!!! Cin splits on white space so if you entered &quot;100 ls&quot; and used your original syntax...
cin>>a>>buffer;
a = 100
and buffer = ls;

Hope this clears up the confusion about cin!
Sera
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top