Re: reading a line through scanf



Suman wrote:
>
> pete wrote:
> > gyan wrote:
> > >
> > > I want to read a line with white spaces though scanf.
> > > So i used:
> > > scanf("%['/n']",string);
> > >
> > > above is working in one program,
> > > but in other..what may be the reason?
> >
> > #define LENGTH 20
> > #define str(x) # x
> > #define xstr(x) str(x)
> >
> > int rc;
> > char array[LENGTH + 1];
> >
> > rc = scanf("%" xstr(LENGTH) "[^\n]%*[^\n]", array);
> ^
> Just a query, should we not write "[^\n]%*1[^\n]", instead?

No.
That's supposed to eat *all*
of the line characters which exceded LENGTH, if there are any,
up to but not including the newline.

> On my gcc (4.0.0)
> it keeps waiting if I don't specify the length.
> > if (!feof(stdin)) {
> > getchar();
> > }
> > if (rc == 0) {
> > *array = '\0';
> > }
> >
> > /* rc will be either 1, 0, or EOF */
> Neat, really very neat!

/* BEGIN new.c */

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

#define LENGTH 30
#define str(x) # x
#define xstr(x) str(x)

int main(void)
{
int rc;
char string[LENGTH + 1];

fputs("Enter a string with spaces:", stdout);
fflush(stdout);
rc = scanf("%" xstr(LENGTH) "[^\n]%*[^\n]", string);
if (!feof(stdin)) {
getchar();
}
while (rc == 1) {
printf("Your string is:%s\n\n"
"Hit the Enter key to end,\nor enter "
"another string to continue:", string);
fflush(stdout);
rc = scanf("%" xstr(LENGTH) "[^\n]%*[^\n]", string);
if (!feof(stdin)) {
getchar();
}
}
return 0;
}

/* END new.c */


--
pete
.



Relevant Pages

  • Re: returning address of stack variable
    ... pete said: ... You can grep on "variables" in the standard. ... the value of each variable to int size and then add the two int s and ... between a ``variable pointer to a constant value'' and a ``constant ...
    (comp.lang.c)
  • Re: just want detail information
    ... int c,d; ... Pete, did you post this URL to call attention to the apparent ... This collection of hypertext pages is Copyright 1995 by Steve ... made available here by permission of the author and the publisher ...
    (comp.lang.c)
  • Re: Macro for supplying memset with an unsigned char
    ... The point wasn't whether we could assign 65000 to an int, ... because the conversion from unsigned integer types to signed integer ... old posts of yours pete: ...
    (comp.lang.c)
  • Re: reading a line through scanf
    ... pete wrote: ... > gyan wrote: ... >> I want to read a line with white spaces though scanf. ...
    (comp.lang.c)
  • Re: reading byte by byte from memory
    ... pete wrote: ... I 'm coping data from an unsigned short to a char*. ... int main{ ... the value of buf at the server. ...
    (comp.lang.c)