0

我正在尝试读取两个文件“ListEmployees01.txt”和“ListEmployees02.table”。但该程序仅读取“ListEmployees01.txt”文件,并且cout只是从该文件中读取。

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string>
using namespace std;

int main()
{
    freopen("ListEmployees01.txt", "r", stdin);
    string s;
    while (getline(cin, s))
        cout << s<<endl;
    fclose(stdin);
    freopen("ListEmployees02.table", "r", stdin);
    while (getline(cin, s))
        cout << s<<endl;

}
4

3 回答 3

2

您可以使用std::ifstream而不是更改std::cin的行为。

于 2019-12-02T09:33:38.090 回答
1

在您的情况下,对于第二个文件,您使用的标准输入已经被下一行关闭,因此它是文件关闭后的悬空指针

fclose(标准输入)

您可以对第二个文件使用 fopen 而不是 freopen。

请从 www.cplusplus.com/reference/cstdio/freopen/ 查看以下段落

如果指定了新文件名,该函数首先尝试关闭任何已与流(第三个参数)关联的文件并解除关联。然后,无论该流是否成功关闭,freopen 都会打开由文件名指定的文件并将其与流相关联,就像 fopen 使用指定模式所做的那样。

于 2019-12-02T09:52:24.730 回答
1

我会做以下使用fstream

#include <fstream>

void readAndPrint(const char *filename) {

    std::ifstream file(filename);

    if (file.is_open()) {

        std::string line;
        while (getline(file, line)) {
            printf("%s\n", line.c_str());
        }
        file.close();

    }

}

int main() {

    readAndPrint("ListEmployees01.txt");
    readAndPrint("ListEmployees02.table");

    return 0;
}

如果您必须使用freopen,请查看man freopen,或 C++ 参考http://www.cplusplus.com/reference/cstdio/freopen

于 2019-12-02T09:55:06.880 回答