首页 > 解决方案 > 无法使用 fstream 写入文件 - 我似乎不明白为什么

问题描述

我需要使用图论创建一个程序,该程序将多个无向图作为输入,如果它是一个完整的图,则写出 YES,如果它不是一个完整的图,则写出 NO。

例如:

2 //number of graps
3 //number of lines of the first graph's matrix
0 1 1 //the first graph's matrix
1 0 1
1 1 0
4 //number of lines of the second graph's matrix
0 1 1 1 //the second graph's matrix
1 0 0 1
1 0 0 1
1 1 1 0

它应该输出:

YES
NO

我是这样解决的:

#include <iostream>
#include <fstream>

using namespace std;

ifstream f("graf_complet.in");
ofstream g("graf_complet.out");

int verif(int matrice[][100], int t)
{
    int c = 0;
    bool ok = 1;
    for (int i = 1; i <= t; i++)
    {
        c = 0;
        for (int j = 1; j <= t; j++)
        {
            if (matrice[i][j] == 1)
            {
                c++;
            }
        }
        if (c != (t - 1))
        {
            ok = 0;
            break;
        }
    }
    if (ok == 1)
    {
        return 1;
    }
    return 0;
}

int main()
{
    int g, c = 0, t, matrice[100][100];
    f >> g;
    while (c != g)
    {
        f >> t;
        for (int i = 1; i <= t; i++)
        {
            for (int j = 1; j <= t; j++)
            {
                f >> matrice[i][j];
            }
        }
        if (verif(matrice, t))
        {
            g << "YES";
        }
        else
        {
            g << "NO";
        }
        c++;
    }
}

使用 cout 而不是写入文件有效,我似乎得到了正确的结果。当我尝试使用 g<< (我应该这样做)写入文件时,我得到:

Severity    Code    Description Project File    Line    Suppression State
Error   C2297   '<<': illegal, right operand has type 'const char [3]'  ConsoleApplication1 C:\Users\x\source\repos\ConsoleApplication1\ConsoleApplication1\ConsoleApplication1.cpp 52  
Error   C2297   '<<': illegal, right operand has type 'const char [3]'  ConsoleApplication1 C:\Users\x\source\repos\ConsoleApplication1\ConsoleApplication1\ConsoleApplication1.cpp 56  
Error (active)  E2140   expression must have integral or unscoped enum type ConsoleApplication1 C:\Users\x\source\repos\ConsoleApplication1\ConsoleApplication1\ConsoleApplication1.cpp 52  
Error (active)  E2140   expression must have integral or unscoped enum type ConsoleApplication1 C:\Users\x\source\repos\ConsoleApplication1\ConsoleApplication1\ConsoleApplication1.cpp 56  

我不明白为什么会发生这种情况。这不是我第一次以这种方式写入文件,而且我从未遇到过这种情况。我认为这可能是因为我从中获取输入的文件(所以基本上是 f>>)没有关闭,它仍然是打开的。

是这个原因吗?

如果是这样,我怎样才能使程序正常工作?如果不是,导致错误的问题是什么?

谢谢。

标签: c++

解决方案


推荐阅读