KSP Atlas
KSP Atlas

Reputation: 148

Apostrophe gets interpreted as char no matter what in C++

I'm having an issue. Here is the code if you need it:

#include<iostream>
#include<string>
std::string findthis = "I\'m";
std::string input;
int index;
std::string sub = "Hi";
int main() {
    while (true) {
        std::getline(std::cin, input);
        if ((index = input.find(findthis)) != std::string::npos) {
            input.replace(index, 2, sub);
            std::cout << input << ", I'm dad!\n";
        }
    }
}

Yes, it is a simple dad bot program, but I'm learning about search and replace in C++. However, if i try to execute the code, Here is the result:

(me) I'm test
(output) Him test, I'm dad!

Is there any way to fix this?

Upvotes: 0

Views: 481

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596377

"I\'m" is 3 characters in length: I ' m (FYI, you don't need to escape ' in a string literal, only in a character literal). But you are telling replace() to replace only 2 characters, not 3 characters. So, you are replacing I with H, and ' with i, but leaving m unchanged. That is why you are seeing Him instead of Hi in the output.

You need to change this:

input.replace(index, 2, sub);

To this instead:

input.replace(index, findthis.size(), sub);


That being said, there are a few other changes you should make, as well:

  • findthis and sub should be declared const.

  • input and index should not be global variables.

  • index should be std::string::size_type instead of int.

  • while (true) { std::getline(std::cin, input); ... }
    should be changed to:
    while (std::getline(std::cin, input)) { ... }

Demo

Upvotes: 3

Related Questions