我正在尝试读取一个将分别显示数字和字符的字符串。
附加信息:
1. 程序将 10(十)显示为 1 和 0,即两个单独的数字
2.它也把空格算作一个字符,它应该跳过。
3. 如果用户输入 10 20 + 它应该显示:
数字是10
数字是20
其他字符是+
这是我试过的
#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");
}
编辑现在变成:
#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");
}
不工作g
最佳答案
您可以改用字符串流。
[...]
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;
}
[...]
}
关于c++ - C++中如何从字符串中读取字符和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8179196/