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 ie 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 +
#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");
}
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
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;
}
[...]
}
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";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.