题解 P5015 【标题统计】
主要是读入
众所周知文件末尾都会读入一个EOF
我们考虑用getchar()读入,判断是否为EOF,如果是当然结束,否则继续
于是我们就有 while (c = getchar() != EOF)
但是我们会发现这样读入是错的
我这道题的读入方式: while ((c = getchar()) != EOF)
搞定读入之后,我们只需要做简单判断就可以了
Accepted code:
#include<cstdio>
using namespace std;
int ans; char c;
int main() {
while ((c = getchar()) != EOF)
ans += (c != ' ' && c != '\n');
printf("%d", ans);
}
其实可以这么理解:
#include<cstdio>
using namespace std;
int ans; char c;
int main() {
while (1) {
c = getchar();
if (c == EOF) break;
if (c != ' ' && c != '\n')
ans++;
}
return printf("%d\n", ans) & 0;
}