+ 2
Unable to key-in full name
Hi im doing a C language program. I use: char name[30]; Printf ("Enter name:"); scanf("%d", &name); When i keyin my full name example, Dwayne Johnson.. The output only display "Dwayne"
15 Respostas
+ 4
You can do it for example this way.
https://code.sololearn.com/c00CGLH1x5Dx/?ref=app
Hope it helps you 😉
+ 4
As stated here[1], the use of `[^characters]` specifier or "negated scanset" has described as a format specifier to accept user's input up to the first occurrence of the `character` being indicated inside the brackets. It actually a dangerous way to perform such operation with a fixed buffer due to the possibility of buffer overflow. Also, the compiler would truly frown about the fact that the variable `name` has a format as `char (*)[30]` instead of `char *` and it somehow warns us to reconsider our approach and make it safe. However, if we are persistent to make our code vulnerable, there's one last resort to tell the input stream about the limitation of our buffer like this
scanf("%28[^\n]", name);
Here, any input with a length above 28 characters would be trimmed out. (29th character is '\0').
[1] http://www.cplusplus.com/reference/cstdio/scanf/
+ 3
Hi TheWh¡teCat ! Thanks for your support!
What's [^\n] for btw?
+ 3
ARJ96 , it matches everything in a string including whitespaces until line break is reached.
+ 3
This is a live example which shows us the point I mentioned earlier. If you have difficulty in understanding any part of the code, please feel free and ask.
#include <stdio.h>
int main() {
char name[10];
printf ("Enter name:");
if ( scanf("%9[^\n]", name) )
printf("%s\n", name);;
return 0;
}
Input: Hello, World!
Output: Hello, Wo
The output is 9 visible characters + one null character
Live: https://rextester.com/ZIKY42960
+ 2
Thanks Théophile I'll try that out later on
+ 2
TheWh¡teCat how about integer? I want to key in my ID. How to declare that?
+ 2
For example 75890-123-4567
+ 2
ARJ96 , you can read it as string. Look again in the code with added id part.
https://code.sololearn.com/c00CGLH1x5Dx/?ref=app
+ 2
ARJ96 , you are welcome 😉
+ 1
And with fgets :
fgets(&name, 30, stdin);
+ 1
TheWh¡teCat any ideas?
+ 1
My friend TheWh¡teCat you're my saviour!! TQVM!!!
+ 1
I thought for number could use int but looks like using char solved my problem!
+ 1
To Seek Glory in Battle is Glorious Thanks! I'm still a bit blur on your explanation. I hope I'll get to understand that.