0

Hello so I'm basically trying to do something like this.

PrintOpt("Hello | I | Am | Awesome");

and in my PrintOpt code

void PrintOpt(char* Text){
     if(!strcmp(Text, " | ")){
           Text = "\n";
     }
     printf(Text);
}

I would like it to print out like this

Hello
I
Am
Awesome
(On a new line)

But when I do this it doesn't print out anything. Does anyone know why this isn't working? Thank you

Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
Ambition
  • 11
  • 2
  • Do you mean you want every word on its own line? I.e. every instance of `|` is replaced with `\n`? – BoBTFish Feb 05 '15 at 21:37
  • Yes exactly. I tried everything dude :/ – Ambition Feb 05 '15 at 21:38
  • 1
    That sounds more like *replacing* than *deleting*. – Drew Dormann Feb 05 '15 at 21:41
  • 1
    Why are you using C-style strings in a C++ program? You're likely just to get a big pile of answers saying "use std::string". – Carl Norum Feb 05 '15 at 21:41
  • 1
    Dude, this is C code, not C++. I would suggest taking a step back and reading up on string and pointers. – OldProgrammer Feb 05 '15 at 21:41
  • Sorry, I'm just a beginner at this. I don't really know the difference. – Ambition Feb 05 '15 at 21:43
  • possible duplicate of [Split a string in C++?](http://stackoverflow.com/questions/236129/split-a-string-in-c) – Don Larynx Feb 05 '15 at 21:43
  • Right now you're passing the address of a string literal. Attempting to modify the content of that string literal will give undefined behavior, so most of the advice about *how* to do this will almost inevitably fail until/unless you pass something that can be modified safely. – Jerry Coffin Feb 05 '15 at 21:44

4 Answers4

5

Use the std::string replace method

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
2

First of all you should not pass string literal "" as char * and especially try to modify that data. Use std::string instead:

void PrintOpt(std::string Text){
     while( true ) {
         size_t pos = Text.find( " | " );
         if( pos == std::string::npos ) break;
         Text = Text.replace( pos, 3, "\n" );
     }
     std::cout << Text;
     // or printf(Text.c_str()); if you insist on printf()
}
Slava
  • 43,454
  • 1
  • 47
  • 90
  • Almost exactly what I was about to post. Although I did the `find` and check against `npos` in the `while` condition. – BoBTFish Feb 05 '15 at 21:48
0

In the statement "if(!strcmp(Text, " | ")) you get a false. Then you make the variable Text take the value "\n" and you print it (\n is the equivalent of a new line). I guess that's why it doesn't work as expected.

To replace characters you could use the function std::replace.

SaraVF
  • 312
  • 4
  • 6
0

I think you must use strcmp on the every character of string and not all of it at once.

Coldblue
  • 144
  • 2
  • 8