1

I'm trying to read a string that will show digits and characters separately.

Additional Info:
1. the program is showing 10 (ten) as 1 and 0 i.e two separate digits
2. It is also counting space as a character, which it should skip.
3. If a user input 10 20 + it should display:
digit is 10
digit is 20
other Character is +


Here is what I've tried
#include <iostream>
#include <string>
using namespace std;

int main() {
    string s("10 20 +");
    const char *p = s.c_str();
    while (*p != '\0')
    {
        if(isdigit(*p))
        {
            cout << "digit is: "<< *p++ << endl;
        }
        else
        {
            cout<<"other charcters are:"<<*p++<<endl;
        }

    }

    system("pause");
}

Edit Now it becomes :

#include <iostream>
#include <string>
using namespace std;

int main() {
               string x;
string s("1 2 +");
const char *p = s.c_str();
while (*p != '\0')
{
while(isspace(*p)){
                   *p++;
      if(isdigit(*p))
      {
                     while(isdigit(*p))
                     {

                                 x+=*p++;
                                        cout << "digit is: "<< x<< endl;
            }

       }

       else{
            while(!isdigit(*p)&& !isspace(*p))
            x+=*p++;
            cout<<"other charcters are:"<<x<<endl;
            }
}
}
system("pause");
}

Not workingg

Muhammad Arslan Jamshaid
  • 1,077
  • 8
  • 27
  • 48

2 Answers2

2

You could use a stringstream instead.

[...]
stringstream ss;
ss << s;
while(!ss.eof())
{
    char c = ss.peek(); // Looks at the next character without reading it
    if (isdigit(c))
    {
        int number;
        ss >> number;
        cout << "Digit is: " << number;
    }
    [...]
}
Cpt. Red
  • 102
  • 3
1

While the character is space (check the isspace function) skip it.

If the current character is a digit, then while the current character is a digit put it in a temporary string. When the character is no longer a digit, you have a number (which might be a single digit).

Else if the character is not a digit or not a space, do the same as for numbers: collect into a temporary string and display when it ends.

Start over.

Edit Code sample on request:

std::string expression = "10 20 +";
for (std::string::const_iterator c = expression.begin(); c != expression.end(); )
{
    std::string token;

    // Skip whitespace
    while (isspace(*c))
        c++;

    if (isdigit(*c))
    {
        while (isdigit(*c))
            token += *c++;
        std::cout << "Number: " << token << "\n";
    }
    else
    {
        while (!isidigit(*c) && !isspace(*c))
            token += *c++;
        std::cout << "Other: " << token << "\n";
    }
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621