Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with limiting a string length in C

Tags:

c

c-strings

scanf

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);
like image 948
BrandonCanCode Avatar asked Apr 19 '26 05:04

BrandonCanCode


2 Answers

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:

  • Difference between scanf and scanf_s
  • String input using C scanf_s

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.
}
like image 175
RobertS supports Monica Cellio Avatar answered Apr 21 '26 17:04

RobertS supports Monica Cellio


Strings

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.

like image 35
foggynight Avatar answered Apr 21 '26 19:04

foggynight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!