Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   GetString function (http://www.go4expert.com/forums/getstring-function-t28700/)

andi_help 10Jul2012 01:12

GetString function
 
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

xpi0t0s 11Jul2012 12:13

Re: GetString function
 
>>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 12Jul2012 03:43

Re: GetString function
 
Thanks for explanation!


All times are GMT +5.5. The time now is 10:19.