954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

getchar()

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);
}
tufzz
Newbie Poster
8 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

> 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.

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

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. :)

devnar
Junior Poster
149 posts since Sep 2008
Reputation Points: 124
Solved Threads: 18
 
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.

grumpier
Posting Whiz in Training
211 posts since Aug 2008
Reputation Points: 193
Solved Threads: 32
 

>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. :)

devnar
Junior Poster
149 posts since Sep 2008
Reputation Points: 124
Solved Threads: 18
 

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

int i = 0;
while ((string[i++] = getchar())!='\n');
string[i]='\0';
Sci@phy
Posting Whiz in Training
279 posts since Sep 2008
Reputation Points: 110
Solved Threads: 43
 

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);
}
HiHe
Posting Whiz in Training
236 posts since Oct 2008
Reputation Points: 137
Solved Threads: 22
 

> 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
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

Just modifying Sci@phy's code...

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


This will do the trick...

ahamed101
Junior Poster
117 posts since Jul 2008
Reputation Points: 51
Solved Threads: 14
 

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';
ahamed101
Junior Poster
117 posts since Jul 2008
Reputation Points: 51
Solved Threads: 14
 

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

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 
> 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[i]='\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...

ahamed101
Junior Poster
117 posts since Jul 2008
Reputation Points: 51
Solved Threads: 14
 
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 stopgiving 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.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

Salem is right Here

seo services
Newbie Poster
6 posts since Oct 2008
Reputation Points: 10
Solved Threads: 0
 

> 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.

HiHe
Posting Whiz in Training
236 posts since Oct 2008
Reputation Points: 137
Solved Threads: 22
 

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

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

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);
}
cthoes
Light Poster
28 posts since Dec 2009
Reputation Points: 8
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You