+ 11

scanf()

How can I input data using scanf() and char *string; char * string; // char pointer char str[10]; // char array scanf("%s",string); // input on this adrees, not work scanf("%s",str); // input from first addreess , work I don't want to write bordered array [10], I want it would include exact number of text's symbols.

9th Jan 2019, 9:09 AM
GiGeNCo
GiGeNCo - avatar
10 ответов
+ 8
If you use C++ you don't need to worry about string size, just use std::string and it will automatically adjusts its buffer size to fit the input. If you use C then I'm not sure how you can deduce the input length to allocate exact number of bytes needed to store the input before reading it. But perhaps there will be others having more experience who knows how to do that.
9th Jan 2019, 10:03 AM
Ipang
+ 7
" scanf("%s",str); // input from first addreess , work " This line still puts your program in the danger of stack overflow (stack corruption) due to the use of unspecified width for `%s` specifier. With a buffer as `char str[10];` you must specify at most `9` chars width to trim the longer inputs + preserving a single char for '\0' (null terminator) like so scanf("%9s", str); Input: 123456789abcdef str[0] = '1' str[1] = '2' str[2] = '3' str[3] = '4' str[4] = '5' str[5] = '6' str[6] = '7' str[7] = '8' str[8] = '9' str[9] = '\0'
10th Jan 2019, 9:08 AM
Babak
Babak - avatar
+ 4
1. char 2. scanf 3.%s
8th May 2021, 12:57 PM
BIBEK KUMAR SAH
BIBEK KUMAR SAH - avatar
+ 3
Ipang I using C :/
9th Jan 2019, 10:04 AM
GiGeNCo
GiGeNCo - avatar
+ 3
GiGeNCo You can get input from user dynamically if you use getchar https://code.sololearn.com/cViPoPhBTG48/?ref=app
9th Jan 2019, 12:30 PM
Bamberghh
Bamberghh - avatar
+ 3
Scanf() is a way to manipulate memory, i am studying that stuff at the moment. No one should use scanf() Even printf() can be exploitet, if you can access the memory. Its really exiting to do that. Maybe play a little bit on your computer with scanf. I could overflow that stuff and run a sudo command after that. That's so funny.
9th Jan 2019, 10:11 PM
Hotwire
Hotwire - avatar
+ 2
trouble is that “string” doesn’t have any space allocated to it. scanf doesn’t do any buffer checking. if you typed 20 characters into a variable with inly 10 allocated, you end up with big problems, (buffer overflow). There’s a whole thread, and more, on bad C functions: https://stackoverflow.com/questions/1253053/cs-bad-functions-vs-their-good-alternatives
9th Jan 2019, 4:11 PM
Dave Smith
+ 2
Fill in the blanks to declare two strings and assign values from input using the scanf() function. --- str1[20]; char str2[30]; --- ("%s --- ", str1, str2); The answer is; char scanf %s
28th Feb 2023, 11:38 AM
Jembere Guta
Jembere Guta - avatar
0
C++ Soldier (Babak) Thank you very much
10th Jan 2019, 11:25 AM
GiGeNCo
GiGeNCo - avatar
0
Fill In The Blank To Output The Single Character. Char C = 'S'; (C);
7th Jun 2022, 6:25 PM
Julius