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);
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.
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With