Input and Output in C/C++
1. 标准输入输出
scanf()返回值为输入变量个数,终止输入使用Ctrl+z(等于输入EOF或-1)。
#include<stdio.h>
int main() {
int x;
while (scanf("%d", &x) == 1) {
printf("%d\n", x);
}
return 0;
}
cin返回值为cin,终止输入使用Ctrl+z。
#include<iostream>
using namespace std;
int main() {
int x;
while (cin >> x) {
cout << x << endl;
}
return 0;
}
2. 文件输入输出
若令fin=stdin;fout=stdout;则可以将文件输入输出转变为标准输入输出。
#include<stdio.h>
int main() {
FILE *fin;
FILE *fout;
fin = fopen("t.in", "r");
fout = fopen("t.in", "w");
int x;
while (fscanf(fin, "%d", &x) == 1) {
fprintf(fout, "%d\n", x);
}
fclose(fin);
fclose(fout);
return 0;
}
若令#define fin cin #define fout cout 则可以将文件输入输出转变为标准输入输出。
#include<fstream>
using namespace std;
ifstream fin("t.in");
ofstream fout("t.out");
int main() {
int x;
while (fin >> x) {
fout << x << endl;
}
return 0;
}
3. 重定向输入输出
#define LOCAL
#include<stdio.h>
int main() {
#ifdef LOCAL
freopen("t.in", "r", stdin);
freopen("t.out", "w", stdout);
#endif
int x;
while (scanf("%d", &x) == 1) {
printf("%d\n", x);
}
return 0;
}
4. 字符输入输出
存在#define EOF (-1)。
#include<stdio.h>
int main() {
int c;
while ((c = getchar()) != EOF) {
putchar(c);
}
return 0;
}
可以用fgetc()替换getchar(),用fputc()替换putchar()。
#include<stdio.h>
int main() {
int c;
while ((c = fgetc(stdin)) != EOF) {
fputc(c, stdout);
}
return 0;
}
5. 字符串输入输出
fgets()返回值为char*,因此需要和NULL比较。该方式字符串长度固定。
#include<stdio.h>
int main() {
char s[100];
while (fgets(s, sizeof(s), stdin) != NULL) {
puts(s);
}
return 0;
}
该方式字符串以空格、tab和回车为界。
#include<iostream>
#include<string>
using namespace std;
int main() {
string s;
while (cin >> s) {
cout << s << endl;
}
return 0;
}
6. 字符串格式化
#include<stdio.h>
int main() {
char s[100];
sprintf(s, "%d+%d", 3, 4);
printf("%s\n", s);
return 0;
}

浙公网安备 33010602011771号