2013-04-16 32 views
0
切换

我想前面加上数字来了“的putchar”部分,但因为getchar函数是在同一时间抓住一个字符,输出为“喜”变成1 h 2 i的getchar,在C

int linecount = 1; 
int numberflag = 1; 


while (1){ 
    int input = getchar(); // use int to make sure var input is big enough to hold EOF plus any other char 


    switch (input) { 
    case EOF: 
     exit(-1); 

    default: 
     if (numberflag){ 
     printf("\t%d\t", linecount); 
     linecount++; 
     } 
     putchar(input); 
     break; 
    } 
} 

所有帮助将不胜感激。我试图使输出:

1 hi 
2 hello 

,而不是

hi 1 
hello 2 
+0

您需要设置'n umberflag'取决于你得到的'char'。 –

+0

什么是数字标记,它来自哪里? – Lundin

+0

case'\ n':linecount ++ – BLUEPIXY

回答

3

这似乎工作:

#include <stdio.h> 

int main(void) 
{ 
    int linecount = 1; 
    int numberflag = 1; 
    int sol = 1; 
    int c; 

    while ((c = getchar()) != EOF) 
    { 
     if (numberflag && sol) 
     { 
      printf("\t%d\t", linecount++); 
      sol = 0; 
     } 
     if (c == '\n') 
      sol = 1; 
     putchar(c); 
    } 
    return 0; 
} 

输出时,对自己的源代码(./sol < sol.c)运行

 1  #include <stdio.h> 
     2 
     3  int main(void) 
     4  { 
     5   int linecount = 1; 
     6   int numberflag = 1; 
     7   int sol = 1; 
     8   int c; 
     9 
     10   while ((c = getchar()) != EOF) 
     11   { 
     12    if (numberflag && sol) 
     13    { 
     14     printf("\t%d\t", linecount++); 
     15     sol = 0; 
     16    } 
     17    if (c == '\n') 
     18     sol = 1; 
     19    putchar(c); 
     20   } 
     21   return 0; 
     22  }