条注释功能

问题描述 投票:0回答:1

我在函数中调用文件时给我一个错误,该文件是一个cpp文件,忘了算法,我的问题是为什么在函数中调用cpp文件时为什么给我一个错误?

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

void stripComment(ifstream &comm)
{
    string line;
    ifstream inStream;
    ofstream outStream;
    inStream.open("comm.cpp");
    while (comm)
    {
        cin >> line;
    }
    cout << line;
    inStream.close();
}

int main()
{
    ifstream inStream;
    ofstream outStream;
    stripComment("comm.cpp");
}
c++ fstream
1个回答
0
投票

如果您查看编译器,它将确切告诉您问题出在哪里:

In function 'int main()':
23:18: error: invalid initialization of reference of type 'std::ifstream&' {aka 
'std::basic_ifstream<char>&'} from expression of type 'const char [9]'
   23 |     stripComment("comm.cpp");
      |                  ^~~~~~~~~~

编译器告诉您的是,stripComment期望的类型是std::ifstream&,但您给它提供了一个const char*,它不能转换为std::ifstream&,这就是为什么它不会编译的原因。您需要做的就是将参数类型更改为const char*const std::string&,然后它将遇到不同的问题(与您的算法有关)。

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

void stripComment(const std::string &comm)
{
    string line;
    ifstream inStream;
    ofstream outStream;
    inStream.open("comm.cpp");
    while (comm)
    {
        cin >> line;
    }
    cout << line;
    inStream.close();
}

int main()
{
    ifstream inStream;
    ofstream outStream;
    stripComment("comm.cpp");
}
In function 'void stripComment(const string&)':
11:12: error: could not convert 'comm' from 'const string' {aka 'const 
std::__cxx11::basic_string<char>'} to 'bool'
   11 |     while (comm)
      |            ^~~~
      |            |
      |            const string {aka const std::__cxx11::basic_string<char>}

不过,该代码仍然无法编译,因为现在您正在使用const std::string&,就好像它是bool。同样,std::string不能转换为bool,因此只需将comm切换为inStream,然后将comm放入inStream构造函数即可打开该文件。现在一切正常(我也删除了多余的东西):

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

void stripComment(const std::string &comm)
{
    string line;
    ifstream inStream(comm);
    while (inStream)
    {
        cin >> line;
    }
    cout << line;
}

int main()
{
    stripComment("comm.cpp");
    return 0;
}

现在它将编译正常。但是,它可能不会执行您想要的操作。如果while (inStream){...}存在,则comm.cpp将成为无限循环。

© www.soinside.com 2019 - 2024. All rights reserved.