GetString function

Discussion in 'C' started by andi_help, Jul 9, 2012.

  1. andi_help

    andi_help New Member

    Joined:
    Jul 9, 2012
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hi all,
    I started to program with C and have some programming in JAVA. However, I have a small understanding problem with the following simple code below.
    I understand that at the command "while (isspace(ch=getc(in)))" the programm reads till if founds a character that is either a " or a blank. This symbol is assigned to the variable delim.
    Is it then correct to say that the program starts again at the same position as before and continues to read the string till "((ch=getc(in))!=delim)" is fulfilled?

    Code:
    void getString(FILE* in, char str[]){
        char ch, delim;
        int n=0;
        str[0]='\0';
        while (isspace(ch=getc(in)));
        if (ch==EOF) {
            return;
        }
        delim=ch;
    
        while (((ch=getc(in))!=delim) && (ch!=EOF))
            str[n++]=ch;
        str[n]='\0';
    }
    Here ist the small input file:
    "Result A" 4
    "Result B" 5

    Many thanks, Andi
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    >>I understand that at the command "while (isspace(ch=getc(in)))" the programm reads till if founds a character that is either a " or a blank.

    You understand incorrectly. isspace returns TRUE if the character given (which is the one returned by getc and assigned to ch) is a whitespace character, of which there are several: space obviously, but also tab, line feed, carriage return and possibly others. To find out exactly, run something like:
    Code:
    for (int i=0; i<256; i++)
    {
    if (isprint(i) && isspace(i))
      printf("'%c' is a space\n",i);
    }
    
    So the command will loop until ch ISN'T a whitespace character.

    >>Is it then correct to say that the program starts again at the same position as before

    No, getc returns the next character from the file each time it is called, so the first getc after the above while will return the first character after the delimiter. What your code will do, for example, is to read input like " @foo@" and write "foo" to str.
     
    andi_help likes this.
  3. andi_help

    andi_help New Member

    Joined:
    Jul 9, 2012
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Thanks for explanation!
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice