当使用字符串时,c++程序给出一个运行时错误

C++ program gives a run-time error when strings are used

本文关键字:运行时错误 一个 程序 字符串 c++      更新时间:2023-10-16
#include <iostream> 
#include <string.h> 
using namespace std; 
int main () 
{ 
    string st = "Hello world";
    return 0; 
}

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

我尝试在netbeans上使用minGW编译器编译此代码。在成功构建之后,它会显示以下错误:

RUN FAILED (exit value -1,073,741,511, total time: 93ms)

但是当不使用字符串时,它可以干净地工作。我想知道我哪里做错了。

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

#include <string> //c++ string header
int main () 
{ 
    std::string st = "Hello world";
    return 0; 
} 

#include <string.h>是旧的c风格字符串头,很可能不是你想在这里使用的。查看这个问题了解更多细节:和& lt; string.h> ?

注意:如果你真的想要旧的c风格字符串,那么你真的应该使用#include <cstring>,因为这将把这些函数放在std命名空间中,并且不会造成任何命名空间污染,从而导致其他不希望的结果。

可能发生的事情是你使用了旧风格的字符串头,没有正确初始化这些字符串。旧的c风格字符串没有像std::string类那样定义构造函数和操作符=。

编辑:在看了Netbeans论坛之后,这是Netbeans的问题,而不是c++的问题。尝试将输出更改为Netbeans中的外部终端。或者直接从命令行运行程序。如果这些方法不能解决问题或不受欢迎,那么在Netbeans论坛上发布一个帖子。还可以看看这个问题:程序不能在NetBeans中运行,而是在命令行上运行!

us_ #include <string>代替string.h