473,803 Members | 3,752 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

getchar and character arrays

Why I can not begin my subscript of character arrrays with 0.
In this program I can not do :

do
{
na[i]=getchar();
i++;
na[i]=getchar();

} while (na[i]!='\n');
my program :
*-----------------------
void input(char *na)
{

int i=0;

printf ("Enter the name : ");
do
{
i++;

na[i]=getchar();

} while (na[i]!='\n');
}

Dec 7 '06
25 5452
"Jean Pierre Daviau" <On**@WasEno.ug hwrites:
<eh**********@g mail.coma écrit dans le message de news:
11************* *********@n67g2 00...legr oups.com...
>How can I do it with getchar() ?. I know to use it with scanf :
scanf ("\n%c");
That's not correct code. It needs a pointer to char argument.
Transform this to a while with a bouble assignement, plus something of yours

do
{

na[i]=getchar();
i++;
} while (na[i]!='\n');
This isn't correct code either. It sets the element after it sets.
}
Spurious }
--
"Large amounts of money tend to quench any scruples I might be having."
-- Stephan Wilms
Dec 14 '06 #11
eh**********@gm ail.com wrote:
So my my program should be like this after considering your points :
*----------------------------------------------------------------------------------------------
void input(char *na)
{

printf ("Enter the name : ");
do
{

na[i]=getchar();
i++;
} while (na[i]!='\n');
}
No. That won't even compile -- you haven't defined i.

I have commented each of my additions to your code. Consider the
benefits of adding each one.

void input(char *na,
size_t n) /* extra param n tells this function how many
bytes are available in array na points to */
{
size_t i = 0; /* index variable starts at 0 */
int ch; /* ch holds character for the test */

if(n == 0) /* if no space available can only return */
return;
else if(n == 1) /* if only space for null terminator */
{
na[0] = 0;
return;
}

printf("Enter the name : ");

fflush(stdout); /* flushing because no newline was output */

do
{
ch = getchar();
na[i] = ch;
i++;
} while(i < n - 1 /* leave space for null terminator */
&& ch != '\n' /* stop when enter is pressed or */
&& ch != EOF); /* there is an end-of-file or error */

na[i] = 0; /* null-terminate the string */
}

It is important that ch is an int, not a char, because the EOF value is
distinct from the character values in the int returned from getchar. EOF
is a negative number, while the character values are non-negative.

When the result of getchar is assigned to a char, the EOF value (often
-1) and the character 255 often both map to -1. This would result in a
false detection of EOF when the character 255 was read from the stream.

--
Simon.
Dec 14 '06 #12
eh**********@gm ail.com writes:
How can I do it with getchar() ?. I know to use it with scanf :
scanf ("\n%c");
How can you do *what* with getchar()?

If you quoted some of the previous article, I'd probably know what
you're asking.

Please read <http://cfaj.freeshell. org/google/>.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 14 '06 #13
eh**********@gm ail.com wrote:
>
How can I do it with getchar() ?. I know to use it with scanf :
scanf ("\n%c");
What is 'it'? Read the following links.

--
If you want to post a followup via groups.google.c om, ensure
you quote enough for the article to make sense. Google is only
a poor interface to usenet. There is no reason to assume your
readers can, or ever will, see any previous articles.
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
Dec 15 '06 #14
Said before :
no
check for getchar() not return \n before assigning it to n[i]

My question is :

How do I read \n with getchar() before going into the loop below do ..
while.

void input(char *na)
{
printf ("Enter the name : ");
do
{
na[i]=getchar();
i++;
} while (na[i]!='\n');
}
CBFalconer wrote:
eh**********@gm ail.com wrote:

How can I do it with getchar() ?. I know to use it with scanf :
scanf ("\n%c");

What is 'it'? Read the following links.

--
If you want to post a followup via groups.google.c om, ensure
you quote enough for the article to make sense. Google is only
a poor interface to usenet. There is no reason to assume your
readers can, or ever will, see any previous articles.
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
Dec 15 '06 #15
Said before :
no
check for getchar() not return \n before assigning it to n[i]
My question is :
/*-------------------------*/
I want my index to begin with 0 as any C Array as below . How do I read
\n with getchar() before going into the loop below do .. while.

void input(char *na)
{
printf ("Enter the name : ");
do
{
na[i]=getchar();
i++;
} while (na[i]!='\n');
}

CBFalconer wrote:
eh**********@gm ail.com wrote:

How can I do it with getchar() ?. I know to use it with scanf :
scanf ("\n%c");

What is 'it'? Read the following links.

--
If you want to post a followup via groups.google.c om, ensure
you quote enough for the article to make sense. Google is only
a poor interface to usenet. There is no reason to assume your
readers can, or ever will, see any previous articles.
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
Dec 15 '06 #16
Said before :
no
check for getchar() not return \n before assigning it to n[i]
My question is :
I want my index to begin with 0 as any C Array as below . How do I read

\n with getchar() before going into the loop below do .. while.
void input(char *na)
{
printf ("Enter the name : ");
do
{
na[i]=getchar();
i++;
} while (na[i]!='\n');
}


CBFalconer wrote:
eh**********@gm ail.com wrote:

How can I do it with getchar() ?. I know to use it with scanf :
scanf ("\n%c");

What is 'it'? Read the following links.

--
If you want to post a followup via groups.google.c om, ensure
you quote enough for the article to make sense. Google is only
a poor interface to usenet. There is no reason to assume your
readers can, or ever will, see any previous articles.
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
Dec 15 '06 #17
eh**********@gm ail.com wrote:
>
Said before :
no
check for getchar() not return \n before assigning it to n[i]
My question is :
Please don't top-post. Your answer belongs after (or intermixed
with) the snipped material you quote. Many people simply ignore
all top-posted articles. If you want help you should cooperate by
following normal usenet protocol. Read the following links:

--
Some informative links:
<news:news.anno unce.newusers
<http://www.geocities.c om/nnqweb/>
<http://www.catb.org/~esr/faqs/smart-questions.html>
<http://www.caliburn.nl/topposting.html >
<http://www.netmeister. org/news/learn2quote.htm l>
<http://cfaj.freeshell. org/google/>
Dec 16 '06 #18

CBFalconer wrote:
eh**********@gm ail.com wrote:

Said before :
no
check for getchar() not return \n before assigning it to n[i]
My question is :

Please don't top-post. Your answer belongs after (or intermixed
with) the snipped material you quote. Many people simply ignore
all top-posted articles. If you want help you should cooperate by
following normal usenet protocol. Read the following links:

--
Some informative links:
<news:news.anno unce.newusers
<http://www.geocities.c om/nnqweb/>
<http://www.catb.org/~esr/faqs/smart-questions.html>
<http://www.caliburn.nl/topposting.html >
<http://www.netmeister. org/news/learn2quote.htm l>
<http://cfaj.freeshell. org/google/>
oka i am sorry . Is it Oka ?

can I read '\n' using getchar() as I do in scanf ("\n") ?????

please suggested code :
void input (char *n)
////////////////////
{
int i=0;
printf ("\nInput :");
getchar()="\n";
do {
n[i]=getchar();
i++;
} while (n[i]!='\n');
}

void output (char *n)
////////////////////
{
int i=0;
printf ("\noutput :");
do {
printf ("%c" ,n[i]);
i++;
} while (n[i]!='\n');
}

Dec 16 '06 #19
eh**********@gm ail.com wrote:
>
.... snip ...
>
can I read '\n' using getchar() as I do in scanf ("\n") ?????

please suggested code :

void input (char *n)
////////////////////
{
int i=0;
printf ("\nInput :");
getchar()="\n";
do {
n[i]=getchar();
i++;
} while (n[i]!='\n');
}

void output (char *n)
////////////////////
{
int i=0;
printf ("\noutput :");
do {
printf ("%c" ,n[i]);
i++;
} while (n[i]!='\n');
}
Don't use // comments in usenet messages, they can easily be
wrapped and destroy the code. Also try to post complete compilable
programs, with proper indentation. Don't use tabs, because they
are often lost entirely.

'\n' is just another character. If you know that the input
contains an unread one you can flush it with a routine such as the
following:

int flushln(FILE *f) {
int ch;

while ((EOF != (ch = getc(f)) && ('\n' != ch)) continue;
return ch;
}

Calling this guarantees that any '\n' in the input has been
absorbed. It doesn't ensure that there was such to be absorbed.
Note that the input is stored in an int, so that EOF can be
detected. Also note that all input lines (on a buffered system,
which yours almost certainly is) terminate in a '\n'.

Now let us assume that you want to input lines not exceeding some
sort of maximum length, and are willing to discard any input longer
than that maximum. First you must define the maximum length
somewhere:

#define MAXLGH 80 /* just to pick a number out of the hat */

and somewhere you will have a buffer to hold the lines:

char buffer[MAXLGH];

now you want to call a routine to fill that buffer, and discard any
excess length:

void fillbuf(char *buf, int maxlgh); /* A prototype */

(which I haven't used - I combined it with something that prompts)

Putting things together you might end up with a program that looks
like:

#include <stdio.h>
#define MAXLGH 10

/* -------------- */

int flushln(FILE *f) {
int ch;

while ((EOF != (ch = getc(f))) && ('\n' != ch)) continue;
return ch;
}

/* -------------- */

int getinput(FILE *f, char *buf, int lgh, char *prompt) {
int i;
int ch;

fputs(prompt, stdout);
fflush(stdout);
i = 0;
while ((i < lgh) && (EOF != (ch = getc(f))) && ('\n' != ch)) {
/* study the above condition carefully,
especially the order of tests.
Note that with lgh 0 getc is always called */
buf[i++] = ch;
}
/* Now decide why the loop ended. */
if ('\n' != ch) ch = flushln(f);
/* This assumes that EOF is sticky. Don't worry about it */

/* Now we know that any final '\n' has been absorbed */

/* important - terminate the string */
buf[i] = '\0';
return ch;
}

/* -------------- */

int main(void) {

char buffer[MAXLGH + 1]; /* +1 allows for terminating '/0' */
char prompt[] = "Input: ";

while (EOF != getinput(stdin, buffer, MAXLGH, prompt)) {
fputs("Output: ", stdout); /* no appended '\n' */
puts(buffer); /* which appends a '\n' and forces output */
}
return 0; /* main always returns a value */
}

Note that the program terminates on receiving an EOF signal. How
this is done depends on your system. Under linux that will
probably be a CTL-d key. Under MSDOS or Windows that will probably
be a CTL-z key. Entered immediately after the "Input:" prompt.

Lines terminate on receiving a '\n', generated by the Enter key.
Storage terminates either on line termination or receiving MAXLGH
characters.

Aside: It would be well to add a 'static' in the headers of the
functions (other than main), but this won't affect anything until
you get into more complicated multi-file programs.

getchar() is just shorthand for getc(stdin). Routines are more
flexible when you can aim them at arbitrary files. Keep them as
simple as possible.

Don't use scanf for interactive input. It will always leave
confusion. When and if you do use it always check its return
value.

Carefully read the descriptions of each standard function I have
called. This includes getc, getchar, puts, fputs, fflush. Note
that they all do simple things.

--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net>
Dec 16 '06 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2245
by: Cam | last post by:
Hi everyone, Before I answer to a (hopefully) helpful reply to this post, I have been rapped over the knuckles for 'top-posting' and I do not wish to be a learner poster who observes poor netiquette as I am a firm believer in consideration .... to this end, could somebody please tell me how I reply to a message without top-posting? Do I need to have my original post selected when I hit the 'reply' button? Here's my question (and...
3
2760
by: Vinicius | last post by:
Hello, the following code does not work: " .... void main(void) { char option; printf("Choose an option: ");
6
1916
by: Luke Wu | last post by:
Whenever one runs across programs that use the return value from getchar() to read input, it's almost always accepted into an int-defined variable. I've read explanations on this and have always used this form. Recently, someone asked me why an int was needed, since -1 (usually EOF) can be safely represented in a signed char value. In fact, any negative number can be safely represented in a signed char value, and wouldn't conflict with...
1
3723
by: White Spirit | last post by:
I'm trying to use getchar() to read alphanumeric data as follows:- char input; /* Take a string of input and remove all spaces therein */ int j = 0; while ((input = getchar()) != '\n') { if (!isspace(input)) j++;
5
8759
by: Jonathan | last post by:
Hi-- I have the following code: #include <stdio.h> char a,b; int main()
6
5281
by: Alan | last post by:
I am using Standard C compiled with GCC under Linux Fedora Core 4 When I run this program and enter a character at the prompt, I have to press the ENTER key as well. This gives me 2 input characters - 'a' and '\n' (Hex 61 and 0a) It seems as though the getchar() function needs ENTER to terminate reading stdin. I am trying to get the program to respond when I press one key only (ie
26
4545
by: tesh.uk | last post by:
Hi Gurus, I have written the following code with the help of Ivor Horton's Beginning C : // Structures, Arrays of Structures. #include "stdafx.h" #include "stdio.h" #define MY_ARRAY 15
12
4726
by: arnuld | last post by:
#include <stdio.h> int main() { printf("%d\n", getchar() != EOF); return 0; } when i run this programme, no matter what i give it as input, output
22
3611
by: arnuld | last post by:
Mostly when I want to take input from stdin I use getchar() but I get this from man page itself: "If the integer value returned by getchar() is stored into a variable of type char and then compared against the integer constant EOF, the comparison may never succeed, because sign-extension of a variable of type char on widening to integer is implementation-defined" while( EOF != (ch = getchar()) ) ....
0
9703
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10555
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10317
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10069
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9127
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6844
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5636
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4277
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3802
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.