Reputation: 13
I'm trying to work on a string comparison check for an introductory C++ course; it's an online course and unfortunately the instructor is not very responsive. For a current lab, I need to perform a number of manipulations on string data.
Currently, I'm working on a step to check if a string has any repeated characters, and if a repetition is found, to delete the repeated characters at their present spot and move one copy of the letter to the beginning of the string. This is only to be done for the first double to be found.
I've set up a basic counter to move through the string looking for matches, checking a stored character (updated on each iteration) to the current position in the string.
I tried multiple string functions (comparing the current inputString[i]
to the previous such, stored as a second string tempStore), but those always gave char conversion errors. I've tried the below instead, but this is now giving an error: "invalid conversion from 'char' to 'const char*
'.
inputString
is given by the user, testA
and testB
are defined as type char
Any ideas?
while (opComplete == false) {
if (i == 0) {
i++;
}
else if (i == inputString.size()) {
//Not Found
opComplete = true;
}
else if (i > 0) {
testA = inputString[i-1];
testB = inputString[i];
if (strcmp(testA,testB) != 0) {
i++;
}
else {
inputString.insert(0,inputString[i]);
inputString.erase(i,1);
inputString.erase(i-1,1);
opComplete = true;
}
}
}
Upvotes: 1
Views: 4178
Reputation: 3695
You are using the insert
method incorrectly, check its reference here for possible arguments.
while (opComplete == false)
{
if (i == 0)
i++;
else if (i == inputString.size())
opComplete = true;
else if (i > 0) {
char testA = inputString[i-1];
char testB = inputString[i];
if(testA!=testB)
i++;
else {
inputString.insert(0,&testB); //Problem Corrected here.
inputString.erase(i,1);
inputString.erase(i-1,1);
opComplete = true;
}
}
}
Upvotes: 0
Reputation: 29966
Your problem is in this line:
inputString.insert(0,inputString[i]);
The std::string.insert()
function the way you call it here has the following signature:
string& insert ( size_t pos1, const char* s );
so it expects a const char
pointer. You, however, are giving it the inputString[i]
. The return value of std::string.operator[]
is a reference (as here), hence the error. However, by the time you reach your else
, you already have the desired character in your testB
variable, so you can just change the line to
inputString.insert(0, &testB);
You also can't pass normal char
s into strcmp
. You can use operator==
, or, in your case, operator!=
though.
Upvotes: 1