How do i prevent a C string input from the user from exceeding the capacity of the array? is this not possible?

int main()
{
char buffer[8];

printf("enter a string");
scanf(%s,&buffer);

return 0;
}

Recommended Answers

All 3 Replies

"%7s" instead of "%s". The field width will limit how many characters scanf reads and places into the array. Or better yet, use fgets for string input.

Use the function fgets().

char *fgets(char *s, int size, FILE *stream);

fgets is best option for taking string input.

commented: Thank you for this useless post. -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.