The Program in C++ Program to insert a Dash Character (-) between two odd numbers in a given string of numbers is given below:
#include <iostream>
#include <string>
std::string insert_dashes(const std::string& str) {
std::string result;
bool prev_odd = false;
for (char c : str) {
if (c >= '0' && c <= '9') {
int num = c - '0';
if (num % 2 == 1) {
if (prev_odd) {
result += "-";
}
prev_odd = true;
} else {
prev_odd = false;
}
result += c;
} else {
prev_odd = false;
result += c;
}
}
return result;
}
int main() {
std::string str;
std::getline(std::cin, str);
std::cout << "Well, the String with dashes inserted are as follows: " << insert_dashes(str) << std::endl;
return 0;
}
Output:
01134528901
Well, the String with dashes inserted are as follows: 01-1-34528901
Pro-Tips💡
This program uses a flag prev_odd
to keep track of whether the previous character was an odd number.
If the current character is an odd number and the previous character was also an odd number, a dash is inserted.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.