使用字符串时,C++程序会产生运行时错误

Din*_*l24 5 c++ string netbeans mingw

#include <iostream> 
#include <string.h> 
using namespace std; 

int main () 
{ 
    string st = "Hello world";
    return 0; 
}
Run Code Online (Sandbox Code Playgroud)

#include <string> 
int main () 
{ 
    std::string st = "Hello world";
    return 0; 
}
Run Code Online (Sandbox Code Playgroud)

我尝试在netbeans上使用minGW编译器编译这段代码.成功构建后会出现以下错误.

RUN FAILED(退出值-1,073,741,511,总时间:93ms)

但是当不使用字符串时它会很干净.我想知道我在这里做错了什么.提前致谢.

shu*_*e87 1

使用 C++ 字符串,不要使用using namespace std

#include <string> //c++ string header

int main () 
{ 
    std::string st = "Hello world";
    return 0; 
} 
Run Code Online (Sandbox Code Playgroud)

#include <string.h>是旧的 C 风格字符串标头,很可能不是您想要在此处使用的。有关更多详细信息,请参阅此问题:Difference Between <string> and <string.h>?

注意:如果您确实想要旧的 C 风格字符串,那么您确实应该使用,#include <cstring>因为这会将这些函数放入std命名空间中,并且不会导致任何命名空间污染,从而导致其他不良结果。

可能发生的情况是您使用了旧式字符串标头并且没有正确初始化这些字符串。旧的 C 风格字符串没有像std::string类那样定义构造函数和运算符=。

编辑:查看 Netbeans 论坛后,这是 Netbeans 的问题,而不是 C++ 问题。尝试将输出更改为 Netbeans 中的外部终端。或者直接从命令行运行程序。如果这些方法不能解决问题或不受欢迎,请在 Netbeans 论坛上发帖。另请看一下这个问题:程序不会在 NetBeans 中运行,而是在命令行上运行!