开发者

C Programming question - Branching

开发者 https://www.devze.com 2023-03-10 21:32 出处:网络
Write a program that reads input up to # and reports the number of times that the se开发者_开发问答quence ei occurs.

Write a program that reads input up to # and reports the number of times that the se开发者_开发问答quence ei occurs.

I have little confusion with sequence such as 'ieei' where compiler does enter 3rd 'e' but never fetches 'i' with getchar(), why and if someone can improve this before myself it'd be good?

char ch;
int sq=0;

while ((ch = getchar()) != '#')
{
    if (ch == 'e')
    {
        ch = getchar();

        if (ch == 'e')
            ch = getchar();

        if (ch == 'i')
            sq++;
    }
}

printf("Sequence occurs %d %s\n", sq, sq == 1 ? "time" : "times");


In my opinion it's simplest to keep the result of the last getchar() in a variable rather than have an extra getchar() inside your loop.

char ch;
int sq=0;
char lastCh = ' ';

while((ch=getChar())!='#') {
  if(lastCh=='e' && ch=='i')
    sq++;
  lastCh=ch;
}

This gives the correct result no matter how many e's in a row or whatever, and breaks at the first # character.


I'm tempted to implement it as:

char ch=0;
int sq=0;

do{
    if( (ch=( ch=='e'? ch:getchar() )) == 'e' && (ch=getchar()) == 'i' )
        ++sq;
}while(ch!='#');

But it uses ?: and && for control flow, which might be confusing especially to beginners.

On second thought it's not that hard to unroll it:

char ch=0;
int sq=0;

do{
    if( ch!='e' ) ch = getchar();

    if( ch == 'e' ){

        ch = getchar();

        if( ch == 'i' ) ++sq;
    }

}while(ch!='#');
0

精彩评论

暂无评论...
验证码 换一张
取 消