Wich syntax is correct?

Dec 18, 2012 at 6:48pm
Hi, in my school I've been learning this kind of syntax:

char Name[21];

int main()
{
printf("What's your name?:\t");
scanf("%[^\n]", &Name);
printf("Well, then hello, world from %s", Name);
system("pause");
return 0;
}


And every time I come here for help I find another type of syntax, the one with the cout, cin and all the << >>.

Can anybody tell me what's the difference? Is it related to the standarizations?

Wich one is more appropiate?

Juan Carlos
Dec 18, 2012 at 6:56pm
The syntax you used is syntax for C, not C++. The cout and con is all c++
Dec 18, 2012 at 7:18pm
cin>>* not con sorry
Dec 18, 2012 at 7:19pm
Dammit, my whole has been a lie. I'll try the tutorial on this page , hopefully I'll learn fast.

Thanks a lot :D
Dec 18, 2012 at 7:30pm
NP
Dec 18, 2012 at 7:52pm
It's allowed (although rarely needed) to use the C-style I/O in a C++ program, but note that even in C, scanf("%[^\n]", &Name); has two errors:

First, &Name is not a pointer to char, it is a pointer to an array of 21 char. The correct syntax is &Name[0] or just Name.

Second, the size of Name is 21 bytes, which means you must use the length specifier: %20[^\n] in this case (20 letters and 1 null terminator), instead of the unlimited %[^\n]. Otherwise someone could type more than 20 characters and cause buffer overrun, which leads to anywhere from crashing to having all your passwords stolen.
Last edited on Dec 18, 2012 at 8:01pm
Topic archived. No new replies allowed.