Reputation: 41
I'm relatively new to coding and do not understand why I'm receiving an Exception thrown with a simple scanf.
char word[15];
printf("\nEnter a word: ");
scanf_s("%15s", word);
Upvotes: 3
Views: 587
Reputation: 11
You're almost there! As you may already know strings in C are stored and managed in memory using an array of chars that terminates with a NULL character ('\0').
In short, if you want to limit the length of your string to say, 15 characters, you just add 1 to that to account for the NULL terminating character and voila! Your code works. A coder's mnemotechnic device:
Desired MAX number of character = Desired MAX number of character + 1;
// or the shortened
the Desired MAX number of character += 1;
Also, bear in mind that, as mentioned above, scanf_s requires an additional argument that specifies the size of the input buffer. So your code would look like:
scanf_s("%16s", word, (unsigned)sizeof( word ));
Hope it helps and happy coding!
Upvotes: 1
Reputation: 73
Strings in C are represented using an array of characters.
These arrays must be terminated using a null character \0
, as the C standard library is written assuming you will be writing strings this way.
When you define the array char word[15]
you are allocating enough memory to store 14 characters plus the null character.
Upvotes: 3
Reputation: 15052
scanf_s
requires a third argument, the sizeof
the buffer:
scanf_s("%s", word, sizeof(word));
scanf_s
can either be Microsoft-specific or the one defined by the C standard but which isn't mandatory to be implemented in every C implementation. Dependent on which one you use you either need to cast the sizeof()
argument to unsigned
(Microsoft implementation) or cast it to rsize_t
(C standard).
Related:
Note that you also should check the return value of scanf_s
.
if ( scanf_s("%s", word, (unsigned) sizeof(word)) != 1 )
{
// error routine.
}
If you want to write portable code, use fgets()
instead:
if ( !fgets(word, sizeof(word), stdin) )
{
// error routine.
}
Upvotes: 7
Reputation: 311048
The function scanf_s
for the conversion specifier s
requires an addition argument that specifiers the size of the input buffer.
You could write for example (if it is the Microsoft implementation of scanf_s)
scanf_s("%14s", word, ( unsigned )sizeof( word ) );
or (if it is the standard scanf_s)
scanf_s("%14s", word, ( rsize_t )sizeof( word ) );
Also the length should be specified equal to sizeof( word ) - 1
that is equal to 14
. One character is reserved for the terminating zero character '\0'
.
Upvotes: 2