<cstdio> is the "C" library (hence <C stdio>) and therefore is more C-oriented.
C did not have the string class. It only had char arrays. Therefore nothing in <cstdio> is built to handle strings. Everything is built to handle char arrays.
This:
scanf("%s",input_name.c_str());
Will not work for many reasons. The main one being that c_str() gives you a read-only version of the string. scanf needs to write to the given buffer.
Furthermore, at this point, 'input_name's buffer has a length of 0 because the string object is empty. So even if that were legal, you would overflow the buffer and corrupt memory. This is one of the fundamental dangers of char arrays and C-style string functions:
you must always be wary of buffer overflows. ALWAYS.
This is why string usage (over char arrays) is generally preferred in modern C++. It's also why <iostream> is generally preferred over <cstdio> in modern C++. Since iostream is built to work with strings, there is no risk of buffer overflows and you never have to worry about allocating enough memory or any of that. It's all done automatically.
makes it a constant or something so i know i cant use that but what do i use? |
You have to use a char array. Then once it's loaded in the char array you can move it to the string.
1 2 3 4
|
char buffer[100];
scanf("%s",buffer);
string input_name = buffer;
|
But again note, you must be wary of buffer overflows. If the user inputs a string longer than 99 characters, you are SCREWED and this code will break. It is very unsafe & is a security risk.
in addition, i cant get whitespace with this as well. |
There's probably a way to get whitespace with scanf, but honestly I don't have the %codes memorized so I couldn't tell you how to do it.
That's another reason why cstdio is often avoided.
Do i really have to use iostream? |
iostream works much better with strings, so you should welcome it. Effective use of iostream is easier and tons safer than trying to mix and match strings with cstdio.
The desired effect with iostream:
1 2
|
string input_name;
getline( cin, input_name );
|
id still rather mess with "strings" and not directly with the character arrays |
Good for you. Now take the same logic you used to form that preference and apply it to iostream
char arrays : strings :: cstdio : iostream