I have a code where the user inputs a string against 2 options.
Dog and Cat
It then checks it against DOG/CAT dog/cat and Dog/Cat and goes to another function depending on the 2 options.
but before it jumps to the next function I want it to change the string to Dog or Cat
So that the carried value wouldn't be DOG or CAT.
So i just want to change a string..
Last edited on
Overkill, perhaps? But if you're normalizing the input string in order to make decisions on it, you may just want to use an enum anyway.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
#include <iostream>
#include <string>
enum Animal { DOG, CAT, UNKNOWN };
Animal getAnimalTypeFromString(std::string animal)
{
if (animal == "DOG" || animal == "dog" || animal == "Dog")
{
return Animal::DOG;
}
else if (animal == "CAT" || animal == "cat" || animal == "Cat")
{
return Animal::CAT;
}
return Animal::UNKNOWN;
}
int main()
{
std::string usrInput;
std::cout << "What kind of animal? (Dog or Cat): ";
std::getline(std::cin, usrInput);
std::string normalizedInput;
switch(getAnimalTypeFromString(usrInput))
{
case Animal::DOG:
normalizedInput = "Dog";
break;
case Animal::CAT:
normalizedInput = "Cat";
break;
case Animal::UNKNOWN:
//intentionall fall-through
default:
std::cout << "Didn't recognize animal type!" << std::endl;
return 1;
}
std::cout << "The string I'm using now is: " << normalizedInput << std::endl;
return 0;
}
|
That's probably ridiculous. This could do just fine.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <iostream>
#include <string>
std::string normalizeInput(std::string animal)
{
if (animal == "DOG" || animal == "dog" || animal == "Dog") { return "Dog"; }
else if (animal == "CAT" || animal == "cat" || animal == "Cat") { return "Cat"; }
else { return "Unknown"; } //or empty string here instead??
}
int main()
{
std::string usrInput;
std::cout << "What kind of animal? (Dog or Cat): ";
std::getline(std::cin, usrInput);
std::string normalizedInput = normalizeInput(usrInput);
std::cout << "The string I'm using now is: " << normalizedInput << std::endl;
return 0;
}
|
Last edited on
obviously i made the question very complicated as all i wanted to do was
string mystring;
mystring = "change";
Thanks anyway, ill take note of your replies.