使用字符串时,C ++程序会给出运行时错误 [英] C++ program gives a run-time error when strings are used

查看:96
本文介绍了使用字符串时,C ++程序会给出运行时错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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编译器来编译此代码.成功构建后会出现以下错误.

I tried compiling this code using minGW compiler on netbeans. It brings up the following error after the successful build.

运行失败(退出值-1,073,741,511,总时间:93ms)

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

但是当不使用字符串时,它可以正常工作.我想知道我在这里做错了什么.预先感谢.

But it works clean when strings are not used. I would like to know what I am doing wrong here. Thanks in advance.

推荐答案

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

Use c++ strings and don't use using namespace std:

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

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

#include <string.h> 是旧的C样式字符串标头,很可能是"t您想在这里使用什么.有关更多详细信息,请参见此问题:< string>之间的差异和< string.h> ;?

注意:如果您真的想要旧的C样式字符串,那么您确实应该使用#include <cstring>,因为这会将这些函数放入std命名空间,并且不会造成任何可能导致其他不良后果的命名空间污染结果.

Note: If you really wanted the old C-style strings then you really should be using #include <cstring> because this will put those functions into the std namespace and won't cause any namespace pollution that can lead to other undesirable outcomes.

发生的事情很可能是您使用了旧样式的字符串标头,并且未正确初始化这些字符串.旧的C样式字符串没有像std::string类那样定义的构造函数和operator =.

Likely what happened was that you used the old style string header and didn't properly initialize those strings. The old C-style strings don't have a constructor and operator= defined like the std::string class.

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

After looking at the Netbeans forum this is a problem with Netbeans and not a c++ issue. Try changing the output to an external terminal in Netbeans. Or run the program directly from the command line. If these approaches don't fix the problem or are undesirable then make a post over on the Netbeans forum. Also have a look at this question: Program won't run in NetBeans, but runs on the command line!

这篇关于使用字符串时,C ++程序会给出运行时错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆