C/C++ 格式化读取和读取一行
文件内容
2
3 2
1 4 1 1 0 11
4 1 1 1 8 11
2 5 0 0 0 11
4 1 0 0 0 11
5 5
2 4 1 0 1 13
4 4 0 1 12 13
1 4 1 1 0 13
3 5 1 1 7 13
一、格式读取
1. C语言
FILE * f_in = fopen("1.txt", "r"); int k; int m, n; int dp[6]; fscanf(f_in, "%d", &k); while (k--) { fscanf(f_in, "%d %d", &m, &n); for (int i = 0; i < 4; ++i) { fscanf(f_in, "%d %d %d %d %d %d", &dp[0], &dp[1], &dp[2], &dp[3], &dp[4], &dp[5]); } }
2. C++ >>输入运算符遇到空白字符就停止输入,但把空白字符留在缓冲区
ifstream f_in("1.txt"); int k; int m, n; int dp[6]; f_in >> k; while (k--) { f_in >> m >> n; for (int i = 0; i < 4; ++i) { f_in >> dp[0] >> dp[1] >> dp[2] >> dp[3] >> dp[4] >> dp[5]; cout << dp[0] << "," << dp[1] << "," << dp[2] << "," << dp[3] << "," << dp[4] << "," << dp[5] << endl; } }
二、读取一行
C++
getline一直读到换行符,从输入缓存读取换行符并把换行符丢弃
ifstream f_in("1.txt"); string str; while (getline(f_in, str)){ cout << str << endl; }
C语言 fgets读取并丢掉换行符
FILE* f_in = fopen("1.txt", "r"); char str[1024]; while (fgets(str, 1024, f_in)){ cout << str; }