'How to replace the digits found in the string(using char variable) with the word corresponding to this digit?
I need help on how to replace the digits found in the string(using the char variable) with the word corresponding to this digit.
For example ab56 to abfivesix
Here is the example
char a;
cout<<"a=";
cin >>a; //im going to enter 'abc345'
The output I want is like abcthreefourfive
I know how to replace it directly but the thing is I'm using cin command so the string is not yet declared
I have an idea to use the switch but have no idea how to start.
Solution 1:[1]
The motivation "im using cin command so the string is not yet declared" makes little sense - there is no difference between a string read from standard input and some other string.
I would do something like this, using a table instead of messing around with switch:
void with_words(std::ostream& os, const std::string& input)
{
static const char* words[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
for (char c: input)
{
if (std::isdigit(c))
{
os << words[c - '0'];
}
else
{
os << c;
}
}
}
Test:
int main()
{
// Output directly.
with_words(std::cout, "abc123");
std::cout << '\n';
// Convert to a different string.
std::stringstream s;
with_words(s, "456def789");
std::cout << s.str() << '\n';
// User input.
std::string in;
std::cout << "? ";
std::cin >> in;
with_words(std::cout, in);
std::cout << '\n';
}
...
$ ./test
abconetwothree
fourfivesixdefseveneightnine
? hell00O0!!1!
hellzerozeroOzero!!one!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | molbdnilo |
