Home > Mobile >  How do i write a program in c that show not allow first name not more than 10 characters?
How do i write a program in c that show not allow first name not more than 10 characters?

Time:10-19

I am trying to create a program to output firstname not more than 5 characters.

#include <stdio.h>
#include <stdlib.h>
int main()
{
     //declaring fisrtname
    char firstname[5];
    printf("Enter your name: ");
    scanf("%s", &firstname);
    printf("\nYour name: %s", firstname);
    return 0;
}

While running a program, i am getting this in my command prompt:

Enter your name: newton

Your name: ←
Process returned 0 (0x0)   execution time : 4.719 s
Press any key to continue.

CodePudding user response:

There are a couple of errors holding you up:

  • The parameter passed into scanf is the wrong type (you are passing a pointer to an array, but it is just expecting a pointer). I would change that line to:
scanf("%s", firstname);
  • The scanf function will happily overflow your filename[5] buffer. The quick fix would be to just up the size of the buffer to something like 256. But to do it the right way you'll need to switch to using something like fgets (passing in stdin), or the likes.
  • To truncate the name to five characters, you will need to write '\0' (the null terminator) to the sixth memory location in the buffer (again, make sure your buffer is large enough).
filename[5] = '\0';

Here is a working version of your code:

#include <stdio.h>
#include <stdlib.h>
int main()
{
     //declaring fisrtname
    char firstname[256];
    printf("Enter your name: ");
    scanf("%s", firstname);
    firstname[5] ='\0';
    printf("\nYour name: %s", firstname);
    return 0;
}
  •  Tags:  
  • c
  • Related