Coder's Guild Mailing List

Re: help with array

Posted by Sharvil Nanavati on 2000-09-26

> Need some assistance here... 
> How do i read in a sentence from user and storing it in an single
> array address. e.g. ' i need help' and store in array[i] using C??
> thanks!
> 
> peter

Well, here are a few solutions:

Solution 1)

int i;
char string[80];
for(i = 0; i < 79; i++)
    string[i] = getch();
string[80] = 0;

Solution 2)

int i;
char string[80];
for(i = 0; i < 79; i++)
    if((string[i] = getch()) == '\n')
        break;
string[i] = 0;

Solution 3)

char string[80];
scanf("%s", string);

The first one reads in a string that is 79 letters long (plus a
terminating NULL character). It does not check for errors, backspaces,
special characters, etc. The string entered MUST be 79 letters long.
The second solution is a little better - it stops when a person presses
the enter key. As with the first one, it doesn't check for errors,
special characters, etc. The third solution is the best one I've
presented - it reads a string and stops when the enter key is pressed.
And it displays whatever the user has typed onto the screen. It handles
backspaces and special characters.

If you want, you could write your own function that uses the second
method, but checks for special characters and stops when a certain key
is pressed (ESC maybe?). Anyway hope this answers your question! :)

Cheers,
Sharvil

__________________________________________________
Do You Yahoo!?
Send instant messages & get email alerts with Yahoo! Messenger.
http://im.yahoo.com/