1
votes

I have a linux box.

On this linux box, there is a program.

In this program, I have a loop like this:

int num=*"what num needs to be"*;
char proc[num];

int result;
while (1) {
result=scanf("%[^'&']%s",proc);
printf("And proc is: %s\n",proc);
printf("Result counter was: %i\n",result)
if (result == 0) break;
}

scanf("%[^'&'],%s",proc)
printf("post lop result is: %s", proc);

As you may have guessed, stdin contains data I need delineated by the '&' character.

As I'm hoping someone more skilled than me has guessed, the output looks something like:

And proc is: *first delineated section*
Result counter was: 1
And proc is: *first delineated section*
Result counter was: 0
post loop result is: *first delineated section*

I thought that scanf was supposed to consume the part of stdin it has already read. Why isn't it doing this?

Also, FYI: this is being run on a very cheap, slow server. Volume may or may not become more than slight. Efficiency is thus a plus, I'm open to however someone might suggest I do this....

Thanks!

2

2 Answers

2
votes

The scanset does not need two single quotes in it — one is sufficient if you want to break on a single quote, but I suspect you only want to stop on &, and the code below assumes that too. Once you've read up to the first &, you need some code to read the &. You need to check the result of scanf() before using the data it returned.

Hence:

int num = 100;
char proc[num];

int result;
while ((result = scanf("%99[^&]", proc)) == 1)
{
    printf("And proc is: <<%s>>\n", proc);
    printf("Result counter was: %i\n", result);
    int c;
    while ((c = getchar()) != EOF && c != '&')
        ;
}

You also need to decide whether newlines mark the end of a field too...if they do, then:

int num = 100;
char proc[num];

int result;
while ((result = scanf("%99[^&\n]", proc)) == 1)
{
    printf("And proc is: <<%s>>\n", proc);
    printf("Result counter was: %i\n", result);
    int c;
    while ((c = getchar()) != EOF)
    {
        if (c != '&' && c != '\n')
        {
            ungetc(c, stdin);
            break;
        }
    }
}

Note the use of %99[...] to prevent buffer overflows. The angle brackets <<%s>> simply mark the start and end of the string; they make trailing blanks and tabs visible, for example.

The code assumes you have a C99 compiler that allows variable declarations midway through a block of code. If not, move int c; to the top of the loop

0
votes

The problem is that on the second iteration the scanf can't read the format you gave it (the line read from standard input does not match) and doesn't modify proc. That's also the reason it returns 0: it has successfully read (and thus modified) 0 fields.