vendredi 1 février 2019

(C++) Program runs over an equality check between values of two strings

I'm making a program that has as input a string of lower case characters and spaces, and takes each character and shows it on screen in the order it appears, separated by a space. Example: If I input "ana has apples" I get an output "a n h s p l". The output I get instead is the input string, just with more spaces, so something like "a n a h a s a p p l e s".

My code is this:

#include <iostream>
#include <string>

using namespace std;

int main()
{
string s, s2;
int i, j;
bool OK;

cout<<"Enter the string: "; getline(cin, s);

for(i=0; i<s.length(); i++)
{
    OK=false;
    for(j=0; j<s2.length(); j++)
        if(s.at(i)==s2.at(j))
            OK==true;
    if(OK==false)
        s2.push_back(s.at(i));
}

for(i=0; i<s2.length(); i++)
    cout<<s2.at(i)<<" ";


return 0;
}

Doing some debugging I found that the problem is at the line if(s.at(i)==s2.at(j)). Even if they are actually equal, the program won't accept the condition as true and turn OK into true, thus pushing back all of the characters from the first string into the second string, having s and s2 be the same. How do I fix this, am I supposed to use a different operator than the classic ==, if so which one? Why is this not working?

Aucun commentaire:

Enregistrer un commentaire