Hey there, I'm trying to write a program that will output the expanded version of text message lingo. For example, if the user inputs "LOL", the output will be "laughing out loud". I'm getting an error that says "comparison with string literal results in unspecified behavior." I have no idea what I'm doing wrong. Here's my code:
int main() {
string userText;
unsigned int i=0;
cout << "Input an abbreviation" << endl;
cin >> userText;
while(i < userText.length())
{
if (userText.at(i)=="LOL") {
userText.replace(i,3, "laughing out loud");
}
if (userText.at(i)=="BFF") {
userText.replace(i,3, "best friends forever");
}
if (userText.at(i)=="IMHO") {
userText.replace(i,4, "in my humble opinion");
}
if (userText.at(i)=="TMI") {
userText.replace(i,3, "too much information");
}
}
cout << "Expanded: " << userText << endl;
getline (cin, userText);
while(i < userText.length())i is not modified in the loop and will thus result in an infinite loop.
getline (cin, userText);
What is the purpose of this? cin >> userText will leave a newline character which will result in getline reading that and skipping your intended input.
Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)).
#include <iostream>
#include <string>
usingnamespace std;
int main() {
string abbreviation[] = {"LOL", "BFF", "IMHO", "TMI"};
string expansion[] = { "laughing out loud","best friends forever","in my humble opinion","too much information" };
size_t limit = sizeof(abbreviation)/ sizeof(string);
size_t index = 0;
size_t position = 0;
string userText;
cout << "Input a line of text: ";
getline(cin, userText);
while (index != limit)
{
position = userText.find(abbreviation[index]);
if(position != std::string::npos)
userText.replace(position, abbreviation[index].length(), expansion[index] );
index++;
}
cout << "Expanded: " << userText << endl;
return 0;
}
Input a line of text: Actually IMHO it works LOL but that's only IMHO
Expanded: Actually in my humble opinion it works laughing out loud but that's only IMHO
Program ended with exit code: 0
This will expand the first of each abbreviation detected in a sentence and can be extended easily to expand multiple instances of the same abbreviation.