The purpose of this code is to insert an x
in between repeating letters. For example, if I were to input "CoolBoolFallmoose"
, the output would be "CoxolBoxolFalxlmoxose"
.
The code is also supposed to make an even number of pairs of letters, so if there is an odd amount of characters, an x
is added to the end of the string. An example for this would be if we had "ball"
, it would become "balxlx"
to make even pairs: "ba"
"lx"
"lx"
.
This is the code I have so far:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
string cipher, plain, paired = "";
cout << "input plaintext(no spaces, lowercase):n";
cin >> plain;
for (int i=0;i<plain.length();i++){
if (plain[i]==plain[i+1]){
plain.insert(i,'x');
}
paired[i]=paired[i];
cout<<paired[i];
}
if (paired.length() % 2!= 0){
paired=+'x';
}
cout<<paired<<endl;
return 0;
}
The output I get is just the same as my input, no "x"
added in any place.
The issue I am having is, every time I try to use the append()
or insert()
function for strings, I get an error from my compiler, which is xCode. Is there another way to solve this code?
EDIT: The error says:
No matching member function to call for insert
It also comes up for append()
.
3
Answers
I don’t really know what you wanted to do with this part:
but otherwise the logic is good. Here is my take on it,
x
is a counter:If you look at the available overloads of
std::string::insert()
, you will see that your statementplain.insert(i,'x');
does not match any of them, hence the compiler error. The overloads that takes a singlechar
require either:an
index
and acount
(you are omitting thecount
)an
iterator
and an optionalcount
There is, however, a couple of overloads that take just an
index
and a value, but they require aconst char*
or astd::string
, not a singlechar
.Also,
paired[i]=paired[i];
is a no-op. Except in your case, sincepaired
has asize()
of 0 since you never append anything topaired
, so actually any access topaired[...]
is undefined behavior.Try this instead:
Demo
A couple of points
First, Although the string.insert function says it takes an int as its first argument it really wants an iterator in this case.
Second, you are inserting elements into your "plain" string which increases its length and you have plain.length within your loop so you create an infinite loop.
Third, insert inserts BEFORE the index so you need to add 1 to I.
The code below will work for your loop:
And as, mentioned below, if you want to handle spaces you can use getline(cin, plain) instead of cin.