Home > Enterprise >  Is there a way to use bools with strings? I want to search for a word in a string, and if it's
Is there a way to use bools with strings? I want to search for a word in a string, and if it's

Time:12-29

I am very new to coding and this is my first language, C . I have an assignment that is really confusing.

The assignment wants me to search the user input of one line for slang words. Ex: TMI or BFF. However, I don't know how to use conditional expressions to do this, and I have tried if-else statements but they end up reading all the statements instead of each one that applies. The code always comes up with a problem for the conditional expression because I honestly have no clue how to use them for strings in this manner. Any help is appreciated!

(Slang terms are required to be capitalized to be read.)

#include <iostream>
#include <cctype>
#include <iomanip>
#include <string>
using namespace std;

int main() {

string userInput;
int textSlang = '0';

cout << "Welcome to the Text Message Decoder!" << endl;
cout << "WARNING! Slang is case-sensitive. Please make sure all slang is fully capitalized!" << endl;
cout << "Enter a single line text message: " << endl;

getline(cin, userInput);

cout << "You entered: " << userInput << endl;

if (textSlang == string::npos) {
   cout << "Error" << endl;
}

else if ((textSlang = userInput.find("IDK" ))) {
cout << "IDK: I don't know" << endl;
}

else if ((textSlang = userInput.find("TTYL" ))) {
cout << "TTYL: Talk to you later" << endl;
}

else if ((textSlang = userInput.find("TMI" ))) {
cout << "TMI: Too much information" << endl;
}

else if ((textSlang = userInput.find("JK" ))) {
cout << "JK: Just kidding" << endl;
}

else if ((textSlang = userInput.find("BFF" ))) {
cout << "BFF: Best friends forever" << endl;
}

else if ((textSlang = userInput.find("LOL" ))) {
cout << "LOL: Laugh out loud" << endl;
}

else if ((textSlang = userInput.find("TYSM" ))) {
cout << "TYSM: Thank you so much" << endl;
}

else if ((textSlang = userInput.find("OMG" ))) {
cout << "OMG: Oh my god" << endl;
}

cout << "END." << endl;

//textSlang = userInput.find("TTYL");
//textSlang = userInput.find("TMI");
//textSlang = userInput.find("JK");
//textSlang = userInput.find("BFF");
//textSlang = userInput.find("LOL");
//textSlang = userInput.find("TYSM");
//textSlang = userInput.find("OMG");


} 

CodePudding user response:

This code:

else if ((textSlang = userInput.find("IDK" ))) {
cout << "IDK: I don't know" << endl;
}

assigns textSlang to 0 IFF userInput begins with IDK. In all other cases it assigns some value other than 0.

And all int values other that 0 evaluate to true.

You want:

else if ((textSlang = userInput.find("IDK" )) != string::npos) {
  cout << "IDK: I don't know" << endl;
}
  • Related