Hi All,

I just wrote a program of string. In the below program every blank space will be replace by char 'x'. The program compiled successfully but it dint not run, give error. What I am doing wrong plz suggest me.

#include<iostream.h>
using namespace std;
int f1( char *st);
int main()
{
        cout<<"in main\n";
        f1("this is a string of base");
        return 0;

}

int f1( char *st)
{
        while(*st)
        {
                if (*st==' ')
                        *st='x';   // <---My doubt is here...
                        cout<<*st;
                st++;
        }
return 0;
}

Error: in main
Bus error (core dumped)

Thanks for your help.

Recommended Answers

All 2 Replies

"this is a string of base" is a string literal. A string literal is a constant. Your code is trying to directly change a string literal; do not try to change things that are constants. The C++ standard says The effect of attempting to modify a string literal is undefined.

The code below works, but since you're using C++ I think you should just switch to std::string

#include<iostream>
using namespace std;
int f1( char *st);
int main()
{
        cout<<"in main\n";
        char in[] = "this is a string of base";
        f1(in);
        return 0;

}

int f1( char *st)
{
  
          while(*st)
        {
                if (*st==' ')
		             *st='x';   // <---My doubt is here...
                cout<<*st;
                st++;
        }
return 0;
}

Thanks for your help and clearing my doubt @Moschops

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.