总 C++ 新手:文件 I/O Boost 和 std 的问题

Total C++ Noob: File I/O Problems with Boost and std

我正在尝试进行夏季模拟项目,但我似乎无法启动文件 I/O。这是我的代码:

std::string line;
std::ifstream F;

int M = 0;    // Model Parameter //

if (F.open (fname)) // Error 1
    std::cout << "Parsing File...";

else {
    std::cout << "***Parsing - ERROR!***" << std::endl;
    std::cout <<"Invalid filename passed to Parsing::ReadData" << std::endl;
    std::cout << "fname = " << fname << " : Can't open file!" << std::endl;
    throw 2;
}

std::getline (F, line);

std::vector<std::string> *result;
boost::split(result, line, boost::is_any_of(":")); // Errors 2 and 3

// Read Number of Metabolites
M = std::atoi(result[1]);  // Error 4

std::cout << "M = " << M << std::endl;

F.close();

到目前为止,根据我在网上阅读的内容,这对我来说似乎非常简单。让我知道我是否应该提供任何澄清。我在编译和执行时遇到了所有这些错误:

In file included from test_parsing.cpp:11:
./Parsing_Engine.h:72:6: error: value of type 'void' is not contextually
      convertible to 'bool'
        if (F.open (fname))
            ^~~~~~~~~~~~~~
./Parsing_Engine.h:85:2: error: use of undeclared identifier 'boost'
        boost::split(result, line, boost::is_any_of(":"));
        ^
./Parsing_Engine.h:85:29: error: use of undeclared identifier 'boost'
        boost::split(result, line, boost::is_any_of(":"));
                                   ^
./Parsing_Engine.h:88:22: error: implicit instantiation of undefined template
      'std::__1::vector<std::__1::basic_string<char>,
      std::__1::allocator<std::__1::basic_string<char> > >'
        M = std::atoi(result[1]);
                            ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/iosfwd:216:28: note: 
      template is declared here
class _LIBCPP_TEMPLATE_VIS vector;

对于F.open错误,我不明白为什么没有将void解释为false。对于 Boost 错误,我不明白为什么会这样,因为我使用 brew 安装了库。我不明白结果的隐式实例化是什么意思,尽管我认为如果我能得到提升,这个错误就会消失。

关于我做错了什么的任何提示?另外,抱歉 - 我不确定这是否是用于 Whosebug 的 TMI post.

std::basic_fstream<CharT,Traits>::open 的 return 类型是 void。您不能将其用作条件。 falsetruebool 类型的值。您无法将 void 转换为 bool

您可以将这些行重写为

std::string line;
std::ifstream F(fname);

if (F)
    std::cout << "Parsing File...";
else {
    std::cout << "***Parsing - ERROR!***" << std::endl;
    std::cout <<"Invalid filename passed to Parsing::ReadData" << std::endl;
    std::cout << "fname = " << fname << " : Can't open file!" << std::endl;
    throw 2;
}

错误 2 和 3 可能是由于缺少 include 指令造成的。你必须包括提升 headers.

result 是指向字符串向量的指针。 result[1] 等同于 *(result + 1) 并且它的类型是字符串向量。 std::atoi 期望 C 字符串作为唯一参数。也许你想要

std::vector<std::string> result;
boost::split(result, line, boost::is_any_of(":"));

// Read Number of Metabolites
M = std::stoi(result[1]);

std::stoi 获取 std::string 并将其转换为 int.