我试图将数字添加到“putchar”部分,但由于getchar一次抓取一个字符,“hi”的输出变为1 h 2 i
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 :(得分: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 }