C++ basic_string::_S_construct null 无效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21068758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:27:56  来源:igfitidea点击:

basic_string::_S_construct null not valid

c++

提问by starrystar

I am reading an input file from the command line.

我正在从命令行读取输入文件。

int main(int argc, char **argv)
{
    Scene myScene;
string filename = argv[1];
myScene = Parser(filename);
 ...
}

from another file I use the parser function which is declerated like that;

从另一个文件中,我使用了像这样声明的解析器函数;

Scene Parser(string filename)
{
 string line;
 ifstream myfile (filename.c_str());
 ...
 return scene;
}

I am getting the error; terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_S_construct null not valid

我收到错误;在抛出“std::logic_error”what() 实例后调用终止:basic_string::_S_construct null 无效

Program received signal SIGABRT, Aborted.

程序收到信号 SIGABRT,中止。

I have searched the error. I think it is because of these lines. But I cannot find the actual reason. Can anybody help me?

我已经搜索了错误。我想是因为这些线。但我找不到真正的原因。有谁能够帮助我?

回答by Halim Qarroum

This means that filenameis NULLin Parser, probably because you are not passing any arguments to your program's command line.

这意味着filenameParser,可能是因为你没有传递任何参数到你的程序的命令行。

Make sure to always check whether the expected number of arguments are passed to your program. For instance, you could do :

确保始终检查是否将预期数量的参数传递给您的程序。例如,你可以这样做:

int main(int argc, char *argv[]) {
   if (argc != NUMBER_OF_EXPECTED_ARGUMENTS) {
      exit(EXIT_FAILURE);
   }
   // ...
   string filename(argv[1]);
   Scene myScene = Parser(filename);
   // ...
}

回答by Vlad from Moscow

It is possible that you forgot to specify command line arguments and as the result argv[1] is equal to NULL. You should check whether the user entered command line arguments. For example

您可能忘记指定命令行参数,结果 argv[1] 等于 NULL。您应该检查用户是否输入了命令行参数。例如

int main(int argc, char **argv)
{
    Scene myScene;
    string filename;
    if ( 1 < argc ) filename.assign( argv[1] );