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[];
fscanf(f_in, "%d", &k);
while (k--) {
fscanf(f_in, "%d %d", &m, &n);
for (int i = ; i < ; ++i) {
fscanf(f_in, "%d %d %d %d %d %d", &dp[], &dp[], &dp[], &dp[], &dp[], &dp[]);
}
}

2. C++  >>输入运算符遇到空白字符就停止输入,但把空白字符留在缓冲区

ifstream f_in("1.txt");
int k;
int m, n;
int dp[];
f_in >> k;
while (k--) {
f_in >> m >> n;
for (int i = ; i < ; ++i) {
f_in >> dp[] >> dp[] >> dp[] >> dp[] >> dp[] >> dp[];
cout << dp[] << "," << dp[] << "," << dp[] << "," << dp[] << "," << dp[] << "," << dp[] << 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[];

    while (fgets(str, , f_in)){
cout << str;
}
上一篇:PageRank算法MapReduce实现


下一篇:Nuxt使用axios跨域问题解决方法