freopen和cout创建内部错误

时间:2018-01-16 10:38:36

标签: c++ compiler-errors cout freopen c1001

我试图读取和写入一些文件,但是我得到了错误C1001,内部错误发生在编译器"每次我尝试将std::cout内容添加到我的output.out文件中。

为什么?

(我在预处理器定义中使用_CRT_SECURE_NO_WARNINGS以便能够使用freopen()

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <deque>
#include <array>
#include <vector>

freopen("C:\\somepath\\input.in", "r", stdin);
freopen("C:\\somepath\\output.out", "w", stdout);

int t;
std::cin >> t;
std::cout << t << std::endl;
for (int i = 0; i < t; i++)
{
    int n;
    std::cin >> n;
    std::cout << t << std::endl;
    std::vector <int> x, h;
    x.resize(n);
    h.resize(n);
    for(int j=0;j<n;j++)
    {
        std::cin >> x[j] >> h[j];
        std::cout<< x[j] << h[j] << std::endl;
    }
}
编辑:正如Nighteen所说,我的代码中有一些错误(n ++,没有矢量调整大小,现已更正) 但是这个bug仍然存在于某种程度上: 代码在这种状态下进行编译,但是一旦我尝试将cout放入一个字符串,就会出现同样的问题 比如在<<" "

中添加std::cout<< x[j] << h[j] << std::endl;
in the std::cout<< x[j] <<" "<< h[j] << std::endl;

2 个答案:

答案 0 :(得分:1)

假设您将代码放在主块中,代码在MSVC 15.5.2中编译正常。证明here

即使编译没问题,代码似乎也没有成功。首先,你不能std::cin >> x[j] >> h[j];。创建一个临时变量来存储输入,然后将其推回到向量中:

int input1, input2;
std::cin >> input1 >> input2;

x.push_back(input1);
h.push_back(input2);

您还应该注意,此循环for (int j = 0; j < n; n++)永远不会结束。变量j应该增加,而不是n。无论你想要达到什么目标,这似乎都没有。

答案 1 :(得分:0)

std :: cout是用于输出到控制台的std :: ostream。对于输出到文件,使用类std :: ifstream和std :: ofstream。使用以下语法:

std::ifstream [ifstream_name](constructor parameters);
[ifstream_name] >> [container to store file contents];

std::ofstream [ofstream name](constructor parameters);
[ofstream_name] << [contents to write to file];