-2
I want to make a program that reads a string and returns "+" in front of all the numbers. Example
entree:
a 1 2 b 3
exit:
a +1 +2 b +3
i did it:
#include <iostream>
#include <cctype>
#include <string>
#include <sstream>
using namespace std;
bool isdigit(char c)
{
if(c>='0' && c<='9')
return true;
else
return false;
}
int main ()
{
string str;
cin >> str;
for (int i=0; i < str.length(); ++i) {
if (isdigit(str[i])==true){
cout << " +" << str[i];
}
else
cout << str[i];
}
return 0;
}
But it’s not working. I don’t understand why, for me this logic would work... Can someone explain to me why it doesn’t work?
str[i]
indicates the character of the i position and not a string. Tryif (isdigit(str)==true){
and not position the position, or modify the parameter of its function.– anonimo
tried if (isdigit(str)==true) but did not give either.... ai if I were to change the parameter I would put what? char c?
– ana
in case, when I put a string it is only returning the 1 element
– ana
The problem is that you are trying to read the string with Cin. The first space closes the input. Use:
getline(cin, str);
in place ofcin >> str;
.– anonimo
Aaaah!! Now you have!! Thank you very much!
– ana
Is there any way to analyze larger numbers? For example, if I put 123, it is returning +1 +2 +3 instead of +123.
– ana