I am trying to make a program so that you can enter your name, but I want to limit the amount of characters used to 10. This is what i have so far, and when i press backspace on my program, it doesn't delete the previous character but moves the cursor there.
So can anyone help me to make this type of program which works?

#include <stdio.h>
#include <conio.h>

char Name[10];
int Ch = 0;

void NameF()
{
	printf("Enter Name : ");
	while(Ch < 10)
		{
			Name[Ch] = getch();
			if(Ch > 0 && Name[Ch] == '\b')
				{
					Ch --;
					putch(8);
				}
			else
				putch(Name[Ch]);
				
			if(Name[Ch] == '\r')
				break;
			Ch++;
		}
	printf("\nName : %s", Name);
}

void main()
{
	NameF();
}

Why don't you use the standard C function fgets()? Or are you not allowed to do that?

char name[10];
fgets(name, sizeof(name), stdin);
if( name[strlen(name)-1] == '\n')
   name[strlen(name)-1] = '\0';

Only if the fgets() can terminate once its reached the max limit of characters.

you can do this in scanf itself,

scanf("%10s",Name);

you can do this in scanf itself,

scanf("%10s",Name);

No, don't. Getting used to using scanf() for strings is dangerous because it is too easy to use it wrong. And there is fgets() , which is safer all 'round.

can you please tell me which way it is safer?

I just did. Read the post.

If you use strings then remember you need space for a terminating NUL (0). So to store 10 char would need a buffer 11 char long
Peter

>I want to limit the amount of characters used to 10.
Note the difference between limiting the number of characters used and limiting the number of characters the user can type. The latter is rarely needed, requires excessive work on your part to simulate shell input, and is guaranteed to be non-portable.

With fgets, or some other method that limits the number of characters extracted from the stream, it doesn't matter how much the user types. You can limit the number of characters used to whatever you want without resorting to non-portable code.

>can you please tell me which way it is safer?
Without the field width, scanf is no better than gets in terms of risk for buffer overflow. However, your use of scanf was perfectly safe. Though one thing to keep in mind is the difference between the field width in scanf and the buffer size limit in fgets:

scanf("%5s", a); /* Reads up to 5 characters, then appends '\0' */
fgets(a, 5, in); /* Reads up to 4 characters, then appends '\0' */

fgets assumes the size limit includes space for the terminating null character while scanf assumes the field width refers to actual characters in the stream. This is a ripe location for an off-by-one error.

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.