How to see if a string has numbers

Asked

Viewed 56 times

-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. Try if (isdigit(str)==true){ and not position the position, or modify the parameter of its function.

  • tried if (isdigit(str)==true) but did not give either.... ai if I were to change the parameter I would put what? char c?

  • in case, when I put a string it is only returning the 1 element

  • 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 of cin >> str;.

  • Aaaah!! Now you have!! Thank you very much!

  • Is there any way to analyze larger numbers? For example, if I put 123, it is returning +1 +2 +3 instead of +123.

Show 1 more comment

1 answer

0

Ana,

One letter is one letter string. Use something to read the whole line, like getline().

Still on your program, note that

  • no need to rewrite isdigit() because it is available in C++. You may have to include <ctype.h>
  • as isdigit() returns bool do not need to compare with true
  • keys in single commands are optional

Then it would be enough

#include <iostream>
using namespace std;
int main()
{
    string str = "a 1 2 b 3";
    for (int i = 0; i < str.length();i+=1) 
      if (isdigit(str[i]))
        cout << " +" << str[i];
      else
        cout << str[i];
    return 0;
}

Or maybe something like

#include <iostream>
using namespace std;
int main()
{
    string str = "a 1 2 b 3";
    for (auto& letra : str) 
      if (isdigit(letra))
        cout << " +" << letra;
      else
        cout << letra;
    return 0;
}

which may be easier to read and doesn’t need the index. C++ since 2011 knows that iterate for a significa treat the letters one by one.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.