Can C do it ?

J

James Kuyper

Nick said:
....
Try to distinguish between *explicit* use of pointers; which is what
bpascal mans when he says "pointers" and *implicit* use of pointers
which is what you lot mean. You can call printf() and use arrays
without any knowledge of pointers.

I've pointed out his implicit use of pointers, not so much because of
the importance of understanding how such implicit conversions work, but
to point out to him the ubiquity of pointers in C, and the corresponding
futility of trying to do anything complicated in C without understanding
pointers.
it *still* looks that way to me and I've been programming in C for a
decade
or so. I know (and use) the idiom but I'd never claimed it was
obvious.

When I first learned C, I considered it be a trivial obvious thing that
any entry level C programmer could be expected to understand, since it
is mentioned and fully explained in K&R, and I understood it completely
on first reading. Since that time I've used that construct to screen
dozens of prospective employees, only one of whom was able to properly
answer my questions about how it works and what it does. I've come to
realize that I was wrong about that.
 
F

Flash Gordon

Nick said:
I don't think the syntax helps. I found the syntax confusing as a
beginner
and I'd used Pascal, BCPL and assembler. I had a clear model of the
hardware.

In my case I had programmed in Basic, Pascal, Modula 2, several
different assemblers, Forth, Logo and various other languages before
learning C. I ended up learning it because the only decent compilers for
the processor we were committed to using were C compilers (we had tried
a Pascal one, but it was worse than useless).

I can see that the C syntax can be confusing, which is one reason why
when I want to explain pointers I don't use the C syntax. Instead I use
English and things people are familiar with. That way non-programmers
can understand the concept as well (and I've successfully explained bugs
due to pointer miss-use to non-programmers).
 
B

bpascal123

#include <string.h>

int main(void)
{
     char verb[20];
     int len;

     printf("Verbe : ");
     scanf("%19s", verb);
     len = strlen(verb);

     if (strcmp(verb + len - 2, "er") != 0)
          printf("\"%s\" n'est pas un verbe du premier groupe.\n", verb);
     else {
          char *suj[]  = {"je", "tu", "il", "nous", "vous", "ils"};
          char *term[] = {"e",  "es", "e",  "ons",  "ez",   "ent"};
          int i;
          for (i = 0; i < sizeof suj / sizeof suj[0]; i++)
               printf("%4s %.*s%s\n", suj, len - 2, verb, term);
     }
     return 0;

}


Hi Ben,

It's just way above what i can currently understand. However, it looks
nice !

Thanks,

Pascal
 
J

jameskuyper

It's just way above what i can currently understand. However, it looks
nice !

Either you're overestimating the difficulty of understanding pointers,
or you're underestimating your own capacity to understand them, or you
have no chance whatsoever of ever learning to be a proficient C
programmer - I'm not sure which. Regardless of which of the above
options is true, you're really wasting your time (and ours) by trying
to learn any significant amount of C without first learning a lot more
than you currently know about pointers. There's some baby stuff you
can learn before learning pointers; but your messages imply that
you've already learned everything that's worthwhile learning before
going on to pointers.
 
B

bpascal123

Hello,

Just to say, I'm allergic to pointer, i'm just very carefull as i know
they are very powerfull and C is the language that best uses them and
it might if i keep on learning C to understand some other languages
and get the best of what pointers have. I'm saying again, i have
learning how to programm from scratch 3-4 months ago (15-25 hours a
week). I think the best i'm able to deal with the basics or "baby
stuff" as James in the post above calls it, the less trouble i'll have
with pointers....

Back to business, i found this code there (for those who can read
french...and c) : http://www.siteduzero.com/tutoriel-3-35363-realiser-des-saisies-securisees-grace-a-fgets.html

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


static void purger(void)
{
int c ;
while ( ( c = getchar() ) != '\n' && c != EOF ) ;
}


static void clean(char *chaine)
{
char *p = strchr(chaine, '\n') ;
if (p)
*p = 0 ;
else
purger() ;
}


int main(void)
{
char chaine[20] ;

printf("\n\nEnter some text : \n") ;
fgets(chaine, sizeof chaine, stdin) ;
clean(chaine) ;
printf("\nThe text entered is : '%s' ", chaine) ;

return 0 ;
}

The code above is about cleaning the buffer from '\n' until EOF ( EOF
= CTRL-Z or D ?)

I understand broadly the buffer is about memory managment and is
closer to computer instructions from the processor than RAM. Anything
can go into the buffer : video streaming, printer jobs.


Fgets unlike scanf has a limit in the number of caracters entered ?
However, like scanf, fgets reads and holds '\n'. I'm not sure of the
last one, if someone could confirm it would help.


while ( ( c = getchar() ) != '\n' && c != EOF ) ;
tells to read any newline left (here it would be located in array
"chaine" in main) after the user has entered more or less 20
characters and press ENTER... So, fgets reads <ENTER> or '\n' or EOF
if greater than 20 characters and keeps it in the buffer? So in the
next entry, if '\n' is in left in the buffer, the code will skip the
user's entry.
Then the instruction getchar() tells to grab anything left in the
buffer but '\n', assigns it to a variable c and in the meantime
somehow creates a new buffer that could hold any characters but '\n'.

char *p = strchr(chaine, '\n') ;
strchr returns the position of '\n' in chaine to *p . As i understand
from reading about strchr in webpages, char *p is an array of
characters ? And in this code it will only hold one value : '\n'.

if (p)
It tells to proceed if p is anything but empty or null. And if it's
not null, it assigns 0 in place of '\n'.

purger()
If *p is null, then it looks to empty the buffer from the presence of
'\n' and to do so purger() is called.


I'm not sure if what i understand is correct. I think this code is a
milestone for manipulating text entries and i intend to use it from
now on unless there is something better.

I feel sleepy and i hope what i have written makes some sense.

Thanks,

Pascal
 
B

Ben Bacarisse

Back to business, i found this code there (for those who can read
french...and c) : http://www.siteduzero.com/tutoriel-3-35363-realiser-des-saisies-securisees-grace-a-fgets.html

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


static void purger(void)
{
int c ;
while ( ( c = getchar() ) != '\n' && c != EOF ) ;
}


static void clean(char *chaine)
{
char *p = strchr(chaine, '\n') ;
if (p)
*p = 0 ;
else
purger() ;
}


int main(void)
{
char chaine[20] ;

printf("\n\nEnter some text : \n") ;
fgets(chaine, sizeof chaine, stdin) ;
clean(chaine) ;
printf("\nThe text entered is : '%s' ", chaine) ;

return 0 ;
}

The code above is about cleaning the buffer from '\n' until EOF ( EOF
= CTRL-Z or D ?)

When there is no more input, getchar returns EOF (a negative integer)
to tell you that there is not more input. When you are typing at a
program you can signal that there is to be no more input using the
keyboard, but it is often configurable and it varies from system to
system. Ctrl+Z and Ctrl+D are common.
I understand broadly the buffer is about memory managment and is
closer to computer instructions from the processor than RAM. Anything
can go into the buffer : video streaming, printer jobs.

That is so general it won't help you here. This is all about an input
buffer. Most systems let you prepare a line and send it to your
program when you hit return. This lets you correct errors before the
program sees it. The code you show is all about reading to the end of
a line (usually one full input buffer).
Fgets unlike scanf has a limit in the number of caracters entered ?
However, like scanf, fgets reads and holds '\n'. I'm not sure of the
last one, if someone could confirm it would help.

fgets does (read and store the newline). scanf is very general and
can do either.
while ( ( c = getchar() ) != '\n' && c != EOF ) ;
tells to read any newline left (here it would be located in array
"chaine" in main) after the user has entered more or less 20
characters and press ENTER... So, fgets reads <ENTER> or '\n' or EOF
if greater than 20 characters and keeps it in the buffer? So in the
next entry, if '\n' is in left in the buffer, the code will skip the
user's entry.
Then the instruction getchar() tells to grab anything left in the
buffer but '\n', assigns it to a variable c and in the meantime
somehow creates a new buffer that could hold any characters but
'\n'.

This sounds wrong though it may simply be that you are having trouble
saying it in English. The page you link to explained it all quote
well, I thought, so I am wary of trying to do better in a language
that is not your own.
char *p = strchr(chaine, '\n') ;
strchr returns the position of '\n' in chaine to *p . As i understand
from reading about strchr in webpages, char *p is an array of
characters ? And in this code it will only hold one value : '\n'.

if (p)
It tells to proceed if p is anything but empty or null. And if it's
not null, it assigns 0 in place of '\n'.

purger()
If *p is null, then it looks to empty the buffer from the presence of
'\n' and to do so purger() is called.


I'm not sure if what i understand is correct. I think this code is a
milestone for manipulating text entries and i intend to use it from
now on unless there is something better.

I feel sleepy and i hope what i have written makes some sense.

It is easier to explain backwards rather than in the order you show
the code. The user types some text. You read it using fgets. If it
fits (i.e. the input is not too long) then strchr finds a \n in the
array which gets replaced by the string terminator (0). If the line
is too long for the array, then strchr finds no \n, but you (the user)
have typed more characters than have been read, so the program reads
and that are left (i.e. up to the \n that fgets never saw).

This is only one way to read input. It is useful in some programs and
harmful in others. It all depends on what the program is for. I'd
suggest that throwing input away like this is rarely the best thing to
do, but it can help in simple interactive programs.
 
B

bpascal123

This sounds wrong though it may simply be that you are having trouble
saying it in English.  The page you link to explained it all quote
well, I thought, so I am wary of trying to do better in a language
that is not your own.

Hi,

I'm confused about the very confusing language i used at some point
for that post.
I understand you all by your expertise make this place very lively and
professional as well.

Pascal
 
B

bpascal123

Hi,

I'm confused about the very confusing language i used at some point
for that post.
I understand you all by your expertise make this place very lively and
professional as well.

Pascal

And i understand i'm asking very simple and basic programming
questions and this forum gather people with different level of
expertise. I understand for someone who deals everyday with advanced C
code, it's not always easy to answer basic programming questions.
 
B

bpascal123

This is only one way to read input.  It is useful in some programs and
harmful in others.  It all depends on what the program is for.  I'd
suggest that throwing input away like this is rarely the best thing to
do, but it can help in simple interactive programs.


Hi Ben,

You say there are other ways to do the same thing. This way is not
easy to deal with with little a basic knowledge of getchar and the
buffer. I found an explanation there :
http://ubuntuforums.org/showthread.php?t=1059917

However, why isn't more simple to do :

....
char Txt[20] ;
printf("\nEnter some string : ") ;
fgets(Txt, 20, stdin) ;
cnt = strlen(Txt) ;
...

The last itiration of cnt will always be '\0' ?
So why use getchar() != '\n' when fgets with strlen don't store '\n'.
I don't know if EOF would be read by strlen since i don't know much
about the behavior of EOF.

Thanks,
Pascal
 
U

user923005

This is only one way to read input.  It is useful in some programs and
harmful in others.  It all depends on what the program is for.  I'd
suggest that throwing input away like this is rarely the best thing to
do, but it can help in simple interactive programs.

Hi Ben,

You say there are other ways to do the same thing. This way is not
easy to deal with with little a basic knowledge of getchar and the
buffer. I found an explanation there :http://ubuntuforums.org/showthread.php?t=1059917

However, why isn't more simple to do :

...
char Txt[20] ;
printf("\nEnter some string : ") ;
fgets(Txt, 20, stdin) ;
cnt = strlen(Txt) ;
..

The last itiration of cnt will always be '\0' ?
So why use getchar() != '\n' when fgets with strlen don't store '\n'.
I don't know if EOF would be read by strlen since i don't know much
about the behavior of EOF.

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

int main(void)
{
char Txt[20];
size_t cnt;
printf("\nEnter some string : ");
if (fgets(Txt, (int) sizeof Txt, stdin)) {
cnt = strlen(Txt);
/* Do more stuff here... */
/*
It is possible that the read fails,
in which case Txt might contain unterminated garbage.
*/
} else {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
 
R

Richard Bos

Flash Gordon said:
Someone else pointed out that you can overflow the buffer here. I don't
know about French, but in Britain there are place names a lot more than
20 characters.

He's not reading place names, he's reading verbs. AFAICT there are no
infinitive forms of verbs that are longer than 20 characters in French.
It's still not wise, though, partly because some come close and a typo
is easily made, and partly because someone might feed it something which
isn't a verb at all, intentionally or by accident.

Richard
 
B

Ben Bacarisse

It's best to snip sig blocks (even tiny ones).

You say there are other ways to do the same thing. This way is not
easy to deal with with little a basic knowledge of getchar and the
buffer. I found an explanation there :
http://ubuntuforums.org/showthread.php?t=1059917

However, why isn't more simple to do :

...
char Txt[20] ;
printf("\nEnter some string : ") ;
fgets(Txt, 20, stdin) ;

Two things: (a) it is good to get into the habit removing arbitrary
numbers from your code so I'd write fgetc(Txt, sizeof Txt, stdin) so I
don't need to repeat the 20; (b) always check the return from input
functions -- one day it will save your life.

A good programmer feels nervous about seeing:
cnt = strlen(Txt) ;

after an input call that might not have done anything at all.
..

The last itiration of cnt will always be '\0' ?

Yes, and something like the code above is fine if it suits your
purpose, but the whole point of the other code was to deal with the
situation where the input does not fit. The remaining input
characters are still there in the input buffer and this is, sometimes,
undesirable (sometimes it is exactly what you want).
So why use getchar() != '\n' when fgets with strlen don't store '\n'.

If my program prompts for my name and then my age:

Enter you name: Benjamin Salavador Bacarisse
Enter your age:
Sorry, "acarisse" is not a valid age.

The simple fgets stopped after 19 chars (it used the 20th for the \0)
and when the program tried to get the age (may using scanf("%d",
&age)) the scanf saw the remaining characters.

If, after reading the name, I check if there was a newline (maybe
using strchr(Txt, '\n')) I can take action when the input is obviously
too long (i.e. when there is not newline in Txt). The action I need
might be to throw the data away:

int c;
while ((c = getchar()) != '\n') /* do nothing */;

but this loop won't ever end if there is newline (for example if I
enter "Ben^D^D" on my Linux system). Hence we really need:

while ((c = getchar()) != '\n' && c != EOF) /* do nothing */;
I don't know if EOF would be read by strlen since i don't know much
about the behavior of EOF.

EOF is not a character. It does not get put in the string (in fact it
can't be put into a string[1]). EOF is in int (not a char) designed
so that no valid character can be confused with it[1]. When you type
^D or ^Z or whatever, the program never sees this[2] -- it is an
instruction to the operating system to close the program's input
stream. Since stdin is closed, the next gechar() returns the special
(negative) value EOF.

[1] Except on peculiar hardware that beginners should definitely put
to one side for a while.

[2] Except on very old operating system that are best forgotten.
 
B

bpascal123

It's best to snip sig blocks (even tiny ones).

You say there are other ways to do the same thing. This way is not
easy to deal with with little a basic knowledge of getchar and the
buffer. I found an explanation there :
http://ubuntuforums.org/showthread.php?t=1059917
However, why isn't more simple to do :
...
char Txt[20] ;
printf("\nEnter some string : ") ;
fgets(Txt, 20, stdin) ;

Two things: (a) it is good to get into the habit removing arbitrary
numbers from your code so I'd write fgetc(Txt, sizeof Txt, stdin) so I
don't need to repeat the 20; (b) always check the return from input
functions -- one day it will save your life.

A good programmer feels nervous about seeing:
cnt = strlen(Txt) ;

after an input call that might not have done anything at all.
The last itiration of cnt will always be '\0' ?

Yes, and something like the code above is fine if it suits your
purpose, but the whole point of the other code was to deal with the
situation where the input does not fit.  The remaining input
characters are still there in the input buffer and this is, sometimes,
undesirable (sometimes it is exactly what you want).
So why use getchar() != '\n' when fgets with strlen don't store '\n'.

If my program prompts for my name and then my age:

  Enter you name: Benjamin Salavador Bacarisse
  Enter your age:
  Sorry, "acarisse" is not a valid age.

The simple fgets stopped after 19 chars (it used the 20th for the \0)
and when the program tried to get the age (may using scanf("%d",
&age)) the scanf saw the remaining characters.

If, after reading the name, I check if there was a newline (maybe
using strchr(Txt, '\n')) I can take action when the input is obviously
too long (i.e. when there is not newline in Txt).  The action I need
might be to throw the data away:

  int c;
  while ((c = getchar()) != '\n') /* do nothing */;

but this loop won't ever end if there is newline (for example if I
enter "Ben^D^D" on my Linux system).  Hence we really need:

  while ((c = getchar()) != '\n' && c != EOF) /* do nothing */;
I don't know if EOF would be read by strlen since i don't know much
about the behavior of EOF.

EOF is not a character.  It does not get put in the string (in fact it
can't be put into a string[1]).  EOF is in int (not a char) designed
so that no valid character can be confused with it[1].  When you type
^D or ^Z or whatever, the program never sees this[2] -- it is an
instruction to the operating system to close the program's input
stream.  Since stdin is closed, the next gechar() returns the special
(negative) value EOF.

[1] Except on peculiar hardware that beginners should definitely put
to one side for a while.

[2] Except on very old operating system that are best forgotten.

Hi,

Your reply tells a lot Ben. Many thanks. I started to write the one
below before i read yours. I already have the answer from you about
most questions. So this below would be additional informations.


About getchar() != '\n' it seems gcc under linux needs this more than
gcc(djgpp) in Windows. Although gcc linux and gcc or djgpp in windows
should be the same.


From http://ubuntuforums.org/showthread.php?t=1059917, someone says :

"while (getchar() != '\n');
is that the test - (getchar() != '\n') - gets executed each time you
go round the loop, so this fetches a character and tests it against
'\n', and goes back round to execute the condition again if the first
test fails (i.e. the character is '\n'). One of the key things here is
the semi-colon at the end of the statement - which effectively creates
an empty loop - so the condition (including the getchar() function)."

End of quotes (he and i are beginners)


So far, i understand '\n' is located somewhere in the buffer among
other characters that don't impact futur input from stdin.

And as it is said above, the getchar looks for characters (that are in
the buffer ?). What action does it do then ? It reads, memorized or i
don't know what, these characters from the buffer and skips '\n'.

So at the end, we can say getchar() != '\n' CREATES and fills a new
buffer from reading the current one with while. That new buffer
doesn't include '\n'. I'm not just of this assertion.


Not over, i don't think i'm right from what i have just written. It's
all i can understand. But next it gets worse :

int c ;
while ( ( c = getchar() ) != '\n' && c != EOF ) ;

getchar is supposed to work with characters ? Why c is declared as an
int.?

As Ben has said above (in the previous post), EOF is a number (-1 I
think) . So is it why we need an integer variable (here c) ? (Only to
deal with EOF)

I went through http://c-faq.com/~scs/cclass/notes/sx6c.html 6.2
section deals well with getchar but more with EOF than '\n'.

Variable c gets a char value from getchar. Does it then for each
character it can get fills a new buffer with anything but '\n' and
affects that very current character to variable c.
Why a variable is needed here ? Just to secure the not equal
expression ?


6.2 section from the site above says :
Quote :
"The simple example we've been discussing illustrates the tradeoffs
well. We have four things to do:

1. call getchar,
2. assign its return value to a variable,
3. test the return value against EOF, and
4. process the character (in this case, print it out again).

We can't eliminate any of these steps. We have to assign getchar's
value to a variable (we can't just use it directly) because we have to
do two different things with it (test, and print). Therefore,
compressing the assignment and test into the same line is the only
good way of avoiding two distinct calls to getchar. You may not agree
that the compressed idiom is better for being more compact or easier
to read, but the fact that there is now only one call to getchar is a
real virtue.

Don't think that you'll have to write compressed lines like

while((c = getchar()) != EOF)

right away, or in order to be an ``expert C programmer.'' But, for
better or worse, most experienced C programmers do like to use these
idioms (whether they're justified or not), so you'll need to be able
to at least recognize and understand them when you're reading other
peoples' code."

End of quote

It says "we have to do two different things with it (test, and
print)". I think this assertion is closely related to the code they
run and explain in the same page.

However, with '\n', we just need to test it and not to print it ? So
why is a int variable needed ? The question should be how come int
variable c can be both in getchar() and !=EOF ?

What's the point of testing a int variable against '\n' ? '\n' is a
character, isn't it?

Pascal
 
M

Morris Keesan

On Thu, 20 Aug 2009 20:44:19 -0400, (e-mail address removed)
[lots of stuff asking about getchar(), and testing for EOF and '\n']

int c;
while (((c = getchar()) != EOF) && (c != '\n')) {}

(equivalent to what you wrote, but slightly repunctuated for my
preferences: extra parentheses for clarity, and {} to make it
more obvious that it's an empty while loop).

Yes, the reason c is declared as int is so that we can test it
against EOF, which is guaranteed to be a value different than
anything which can be represented by a char. (Usually implemented
as -1, but that value is not required by any standard).

The reason we do this instead of simply

while (getchar() != '\n') {}

is that it's possible that your standard input stream might end
with no newline character.
 
K

Keith Thompson

About getchar() != '\n' it seems gcc under linux needs this more than
gcc(djgpp) in Windows. Although gcc linux and gcc or djgpp in windows
should be the same.

Yes, they should be the same. The external representation of text
files differs between Linux and Windows, but the end-of-line sequence
should be converted to '\n' on either system. I don't understand what
you mean when you say that one system "needs this more" than the
other.

[...]
And as it is said above, the getchar looks for characters (that are in
the buffer ?). What action does it do then ? It reads, memorized or i
don't know what, these characters from the buffer and skips '\n'.

So at the end, we can say getchar() != '\n' CREATES and fills a new
buffer from reading the current one with while. That new buffer
doesn't include '\n'. I'm not just of this assertion.

There is buffering going on, but it's not something you need to worry
about. getchar() reads the next character from the specified input
stream and returns its value (or returns the value of EOF if there are
no more characters to read). '\n' is just another character as far as
getchar() is concerned.
Not over, i don't think i'm right from what i have just written. It's
all i can understand. But next it gets worse :

int c ;
while ( ( c = getchar() ) != '\n' && c != EOF ) ;

getchar is supposed to work with characters ? Why c is declared as an
int.?

Because getchar() returns an int result.

Suppose you're designing a function that reads the next character from
an input stream and gives you its value. The obvious thing to do is
to return a char value, but that's not enough. You also need to be
able to indicate that there are no more characters to be read. So
it's returning two piece of information: the next character (if any)
and an indication of whether there was a next character.

There are several ways this could be done. It could return a
structure containing a char and some sort of flag. It could take a
pointer argument, and store the flag value via that pointer. It could
store the flag in a global (ick!).

The method chosen by the creators of getchar() was something called
in-band signalling: returning a single result that's big enough to
store *either* a character value or a flag value.

If there is another character to be read, getchar() reads it, treats
it as an unsigned char value (so it's guaranteed to be non-negative),
converts that value to int, and returns it. If there isn't (either
because you've reached the end of the file or because there was an
error), getchar returns the value EOF (typically -1, but the only
guarantee is that it's negative). Assuming that INT_MAX >= UCHAR_MAX,
this single result gives you all the information you need.
As Ben has said above (in the previous post), EOF is a number (-1 I
think) . So is it why we need an integer variable (here c) ? (Only to
deal with EOF)

Yes, only to deal with EOF. If it weren't for the need to store that
extra information, getchar() could return a char.

But note that char is also an integer type; it's just a relatively
narrow one, typically used to hold character codes. C represents
characters as numbers.

[...]
What's the point of testing a int variable against '\n' ? '\n' is a
character, isn't it?

'\n' is a character. It's also an integer. On most systems you're
likely to encounter, it's the ASCII linefeed character), so '\n'==10.
If getchar() reads a newline from its input stream, it returns the
value '\n'.
 
J

James Kuyper

Morris Keesan wrote:
....
Yes, the reason c is declared as int is so that we can test it
against EOF, which is guaranteed to be a value different than
anything which can be represented by a char.

The standard requires that all members of the basic character set are
represented by positive values, but allows char to be signed, and also
allows for an extended character set which may contain characters whose
values could be negative.
The standard does not require that EOF be distinct from all char values,
For a fully conforming implementation which chooses to have INT_MAX <
UCHAR_MAX, if you use getc() to read a byte from the input stream whose
value is (unsigned char)EOF, it must return EOF.
 
B

bpascal123

Hi,

getchar() is still quite obscur. Explanations above make it less
dark... But compiling with getchar under Windows and Linux adds insult
to injury. I don't feel bad running one day Windows and another day
Linux at least for testing code to make it portable.

I assigned myself to make a code work both in windows and linux...

For this getchar understanding task, I tested the code below in this
site :
http://c-faq.com/~scs/cclass/notes/sx6b.html

Under linux, it works as one can expect.

Under windows, i get : the same line over and over saying something
with Null ... and a strange number, the same over and over as if it's
a result from the loop in the code.

The code from the link above :
#include <stdio.h>

/* copy input to output */

main()
{
int c;

c = getchar();

while(c != EOF)
{
putchar(c);
c = getchar();
}

return 0;
}

Under windows, i tried to add this line of code several times in the
code where the system expects an entry : while ( getchar() != '\n' ) ;

I think if someone can tell me why these lines of code don't compile
in my Windows system (i'm using djgpp), it will be a great step for
understanding C.

---

Now again about getchar. I'd like to understand more about the part
where the user enters data with getchar() handling it like in the code
above. The user enters a character or a string of characters and hits
enter and (in linux) the string or characters entered are displayed.

When the user enters a characters, the stdin places it into the buffer
and so on for each character entered until <Enter> is pressed down.
Let say i entered "bcd<Enter>". It goes into the buffer like
'b''c''d''\n' ?

Then it reads first 'b' and what does it do with it ?
Does It just leave it in the buffer as it is since it's not '\n' ...
and right after putchar() prints it on the screen, it does the same
for 'c' until getchar() == '\n' or getchar() = '\n' (i don't which one
is correct getchar() == or getchar() = ).

Does Getchar() read and take '\n' from its location in the buffer ?
Where does '\n' go then ?
Getchar could be seen as "search and destroy" in the buffer (stdin
stream) for any value equal to '\n' otherwise it just leave it as it
is ?

Is there a way to access and take a picture of the buffer ? Let say
with hexa values as descriptions ?

Pascal
 
B

bpascal123

Hi,

getchar() is still quite obscur. Explanations above make it less
dark... But compiling with getchar under Windows and Linux adds insult
to injury. I don't feel bad running one day Windows and another day
Linux at least for testing code to make it portable.

I assigned myself to make a code work both in windows and linux...

For this getchar understanding task, I tested the code below in this
site :
http://c-faq.com/~scs/cclass/notes/sx6b.html

Under linux, it works as one can expect.

Under windows, i get : the same line over and over saying something
with Null ... and a strange number, the same over and over as if it's
a result from the loop in the code.

The code from the link above :
#include <stdio.h>

/* copy input to output */

main()
{
int c;

c = getchar();

while(c != EOF)
{
putchar(c);
c = getchar();
}

return 0;

}

Under windows, i tried to add this line of code several times in the
code where the system expects an entry : while ( getchar() != '\n' )
{}

I think if someone can tell me why these lines of code don't compile
in my Windows system (i'm using djgpp), it will be a great step for
understanding C.

---

Now again about getchar. I'd like to understand more about the part
where the user enters data with getchar() handling it like in the code
above. The user enters a character or a string of characters and hits
enter and (in linux) the string or characters entered are displayed.

When the user enters a characters, the stdin places it into the buffer
and so on for each character entered until <Enter> is pressed down.
Let say i entered "bcd<Enter>". It goes into the buffer like
'b''c''d''\n' ?

Then it reads first 'b' and what does it do with it ?
Does It just leave it in the buffer as it is since it's not '\n' ...
and right after putchar() prints it on the screen, it does the same
for 'c' until getchar() == '\n' or getchar() = '\n' (i don't which one
is correct getchar() == or getchar() = ).

Does Getchar() read and take '\n' from its location in the buffer ?
Where does '\n' go then ?
Getchar could be seen as "search and destroy" in the buffer (stdin
stream) for any value equal to '\n' otherwise it just leave it as it
is ?

Is there a way to access and take a picture of the buffer ? Let say
with hexa values as descriptions ?

Pascal
 
K

Keith Thompson

getchar() is still quite obscur. Explanations above make it less
dark... But compiling with getchar under Windows and Linux adds insult
to injury. I don't feel bad running one day Windows and another day
Linux at least for testing code to make it portable.

I assigned myself to make a code work both in windows and linux...

For this getchar understanding task, I tested the code below in this
site :
http://c-faq.com/~scs/cclass/notes/sx6b.html

Under linux, it works as one can expect.

That's to be expected.
Under windows, i get : the same line over and over saying something
with Null ... and a strange number, the same over and over as if it's
a result from the loop in the code.

Describing a rough approximation of the output you got doesn't do
anybody any good. If you can copy-and-paste the *exact* output (or at
least a portion of it), we have a fighting chance of diagnosing the
problem.
The code from the link above :
#include <stdio.h>

/* copy input to output */

main()
{
int c;

c = getchar();

while(c != EOF)
{
putchar(c);
c = getchar();
}

return 0;
}

With one minor exception, that's perfectly good standard C. The one
exception is that "main()" should be "int main(void)". I advise you
to make that change, but it's very unlikely to be the cause of your
problem; most compilers should treat "int main(void)" and "main()"
essentially identically.
Under windows, i tried to add this line of code several times in the
code where the system expects an entry : while ( getchar() != '\n' ) ;

The code you posted is correct. Other than changing "int main(void)"
to "main()", you shouldn't change it. If it's not working, changing
the code isn't the solution.
I think if someone can tell me why these lines of code don't compile
in my Windows system (i'm using djgpp), it will be a great step for
understanding C.

From your rather vague description above ("the same line over and over
saying something with Null ..."), I assumed you were describing the
program's run-time behavior. Now you're saying the code doesn't
compile. Again, you need to copy-and-paste the *exact* output you're
getting, and tell us exactly what you did to get it.

The code you quoted above should compile without error, and when you
run the resulting program, it should do exactly what it's supposed to
do, namely copy standard input to standard output. It should do this
regardless of whether you're using gcc on Linux or djgpp on Windows.

If you're getting some other result, it's because you're doing
something else wrong, and you haven't given us enough information to
guess what that might be.
Now again about getchar. I'd like to understand more about the part
where the user enters data with getchar() handling it like in the code
above.
[snip]

I suggest you worry about getting the code working first.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,828
Latest member
LauraCastr

Latest Threads

Top