Dinal24
Dinal24

Reputation: 3192

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

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

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

and

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

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

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.

Upvotes: 6

Views: 2291

Answers (2)

shuttle87
shuttle87

Reputation: 15934

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> is the old C-style string header and most likely isn't what you want to use here. See this question for more details: Difference between <string> and <string.h>?

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.

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.

Edit: 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!

Upvotes: 1

user1585121
user1585121

Reputation:

Uss #include <string> instead of string.h

Upvotes: 0

Related Questions