文件内容
2
3 21 4 1 1 0 114 1 1 1 8 112 5 0 0 0 114 1 0 0 0 115 52 4 1 0 1 134 4 0 1 12 131 4 1 1 0 133 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; }