-3
int main()
 {
 int c,nl,nt,Blanks;
 nl = 0;
 nt = 0;
 Blanks = 0;
 while ((c= getchar()) != '5'){
    if (c ='\n')
        nl++;
    if(c='\t')
        nt++;
    if(c = 's')
        Blanks ++;
 }

printf("No of lines is %d \n No of tabs %d \n and no of blanks %d \n",nl,nt,Blanks);

return 0;

输出:

 No of lines is 12 
 No of tabs 12 
 and no of blanks 12 

 RUN SUCCESSFUL (total time: 5s)

输出是输入的任何字符的编号,根本不区分它们。此外,当我使用 EOF 使循环在到达文件末尾时停止时,循环并没有停止,程序继续运行。

4

2 回答 2

3

在 C 中,用于=分配,例如。

x = 5;

并用于==比较。例如。

if (x == 5) { /* do something */ }

如果你用错了,例如。

if (x = 5) { /* do something */ }

这将导致分配,而不是比较。表达式x = 5将始终为true,因为x它是非零的,非零与trueC 中的相同。这意味着/* do something */将始终执行。


还有,'5'不代表EOF,代表人物5。您应该替换'5'EOF.

while ((c = getchar()) != EOF)

除此之外,您似乎正在' '使用's'. 这是错误的。's'表示 C 中的字符s' '表示C 中的space字符。


还有一些建议:这与问题没有直接关系,但是由于您显然是 C 的新手,所以我会给您一个重要的指示。

永远不要使用if没有大括号的语句。例如。

if (/* condition */)
    /* do something */

相反,使用

if (/* condition */) {
    /* do something */
}

我知道它更长,但稍后您可能会决定添加另一行代码,例如。

if (/* condition */)
    /* do something */
    /* do something else */

你会很困惑为什么/* do something else */总是执行,天气/* condition */true不是。

于 2014-07-19T21:51:51.070 回答
1

if的s错了。=您每次都错过了一秒钟if,现在您将值分配给c,这导致true. 此外,您可以使用else if,因为这些案例是专有的。

int main()
{
  int c,nl,nt,Blanks;
  nl = 0;
  nt = 0;
  Blanks = 0;
  while ((c= getchar()) != '5'){
    if (c =='\n')
        nl++;
    else if(c=='\t')
        nt++;
    else if(c == 's')
        Blanks ++;
  }

  printf("No of lines is %d \n No of tabs %d \n and no of blanks %d \n",nl,nt,Blanks);

  return 0;
}
于 2014-07-19T21:42:12.383 回答