I've been trying to read characters from the keyboard using 'getchar()' but my code always misses one character. Can anyone tell me why this is

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {

	char string[50];
	int i;
	printf("Enter a string: ");

	for (i=0; i < strlen(string); i++){
		string[i] = getchar();
	}

	printf("%s", string);
}

> for (i=0; i < strlen(string); i++)
You're lucky this works at all.
string starts off uninitialised, so who knows what strlen() on it will return.

string[i]=getchar(); I don't think this will work properly. getchar() expects you to hit enter after the input of each character which means that '\n' will be left in the input buffer which will be read the next time getchar() executes. Which means that each character will alternate with a '\n'.
I might be wrong though. Feel free to correct me. :)

string[i]=getchar(); I might be wrong though. Feel free to correct me. :)

You're wrong. getchar() does not behave in quite the way you described. Consider yourself corrected.

Salem is right. Once you get past the concern he pointed out, there are also additional problems that the code has no error checking, nor does it terminate the input string with a zero byte.

>You're wrong. getchar() does not behave in quite the way you described.

My bad. Did some research on getchar(). Seems getchar() doesn't need enter to be pressed after the input of each character. It can only see the input buffer after hitting the enter. Gotta get my basics straightened. :)

Comments
Good work :)

It should be like this (yeah, I like writing nonesence):

int i = 0;
while ((string[i++] = getchar())!='\n');
string[i]='\0';

You could do it like that:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE   50

int main(int argc, char *argv[]) {

	char string[SIZE], c;
	int i;

        // just a test
        printf("len = %d\n", strlen(string));  // len = 0

	printf("Enter a string: ");

	for (i=0; i < SIZE; i++){
                c = getchar();
                if (c == '\n'){
                    string[i] = '\0';
                    break;
                }
	    string[i] = c;
	}

	printf("string entered = %s", string);
}

> printf("len = %d\n", strlen(string)); // len = 0
Nope, read my first post again.
string isn't initialised, so your length is junk.
If you get zero, that just makes you lucky.

The rest is getting better though.

Just modifying Sci@phy's code...

while ((string[i++] = getchar())!='\n' && i < SIZE);
	string[i]='\0';

This will do the trick...

I've been trying to read characters from the keyboard using 'getchar()' but my code always misses one character. Can anyone tell me why this is

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {

	char string[50];
	int i;
	printf("Enter a string: ");

	for (i=0; i < strlen(string); i++){
		string[i] = getchar();
	}

	printf("%s", string);
}

This aint right...

for (i=0; i < strlen(string); i++){
		string[i] = getchar();
	}

strlen(string) will have some random number... you dont want that...

> printf("len = %d\n", strlen(string)); // len = 0
Nope, read my first post again.
string isn't initialised, so your length is junk.
If you get zero, that just makes you lucky.

The rest is getting better though.

Salem is right...
String is uninitialised... you get junk for len... for sure...

You could do it like that:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE   50

int main(int argc, char *argv[]) {

	char string[SIZE], c;
	int i;

        // just a test
        printf("len = %d\n", strlen(string));  // len = 0

	printf("Enter a string: ");

	for (i=0; i < SIZE; i++){
                c = getchar();
                if (c == '\n'){
                    string[i] = '\0';
                    break;
                }
	    string[i] = c;
	}

	printf("string entered = %s", string);
}

This is good... but it will take one junk character... try executing this code... and its a bit lengthy code for such an read operation...

better way...

while ((string[i++] = getchar())!='\n' && i < SIZE);
	string[i]='\0';

> better way...
Still two problems
- what happens at EOF
- the loop can exit with i == SIZE, which means your \0 is out of bounds.

> better way...
Still two problems
- what happens at EOF
- the loop can exit with i == SIZE, which means your \0 is out of bounds.

Yes, EOF is an issue... but while entering the character where does EOF comes into picture?...

'\0' is out of bound when i == SIZE..
may be this can correct that..

while ((string[i++] = getchar())!='\n' && i < SIZE);
	string[--i]='\0';

One more thing, with the previous code i.e. string='\0'... the i-1th position will be '\n' and ith position will be '\0' (which is of course out of bound of the array)... just for info...

Salem is right...
String is uninitialised... you get junk for len... for sure...

Then why bring it up. He already had others confirm this. :icon_rolleyes:

Yes, EOF is an issue... but while entering the character where does EOF comes into picture?...

Anytime you pipe in a file or press the EOF keystroke.

This thread is a great examply why people need to stop giving working answers to questions. Lots of code that teaches bad techniques. Just help the original poster find his own answer with hints and suggestions, not poorly designed code.

> printf("len = %d\n", strlen(string)); // len = 0
Nope, read my first post again.
string isn't initialised, so your length is junk.
If you get zero, that just makes you lucky.

The rest is getting better though.

I put that in just to show that one gets zero or nonsense, hence the "just for test" remark in the line above it.

> I put that in just to show that one gets zero or nonsense,
Or the right answer, or a segmentation fault.

i found a one logical mistake in you code since u are finding length of string using strlen() before you put value into it. so what i did was before adding value into string . i define length of string. so using getchar() will receive only that no of character that u request.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {

	char string[50];
	int i,length;
                printf("\n Enter length of string\n");// i added extra code
                scanf("%d",length);                        // extra code
	printf("Enter a string: ");

	for (i=0; i < length; i++){
		string[i] = getchar();
	}

	printf("%s", string);
}

Edited 6 Years Ago by Nick Evan: For easy readability, always wrap programming code within posts in [code] (code blocks) and [icode] (inline code) tags.

This article has been dead for over six months. Start a new discussion instead.