使用getchar()函数

时间:2013-11-30 15:21:42

标签: c++ getchar

我使用getchar()来停止while字符串。我的问题是,如果我键入一个或两个字符,它会停止while字符串,如果用户输入更多,则两个字符都没有发生。

这是代码:

printf("enter srting\n");

while ((tmp=getchar()) !='\n') { \\here is my problem

    count_letters++;
        /* COUNTING WORD THAT START WITH LETTES L,A,C,H */

    while (count_letters%3==0) {
        switch (tmp) {
            case 'A': count_a++;
                break;
            case 'C': count_c++;
                break;
            case 'H': count_h++;
                break;
            case 'L': count_l++;
            default:
                break;
        }
    } /* end of count letters while  */

    n1=n2;
    n2=n3;
    n3=tmp;

    if (n1=='H' && n2=='Y' && n3=='A') {
        count_hya++;
    }



    } /* end of getchar while */
printf("\n");

printf("%d", count_letters);

2 个答案:

答案 0 :(得分:1)

  1. 我相信这是你的代码: “while(count_letters%3 == 0))” 有点不对劲!
  2. 因为当您输入三个以上的字母时,由于代码:“count_letters ++;”,您的变量“count_letters”将添加到3。
  3. 可能是你可以将“while”更改为“if”并查看它是否正常工作〜

答案 1 :(得分:0)

问题在于:

while (count_letters%3==0) {
        switch (tmp) {
            case 'A': count_a++;
                break;
            case 'C': count_c++;
                break;
            case 'H': count_h++;
                break;
            case 'L': count_l++;
            default:
                break;
        }
}

当您读取第三个字符时,由于(count_letters%3 == 0),您的程序进入无限循环

我无法理解您的代码的目的。 我建议使用gets()和字符串操作函数,因为您正在处理整行。 (见string.h)

与gets()+ for-loop

相比,

getchar()的效率也较低