c++ - C++中如何从字符串中读取字符和数字

标签 c++ string

我正在尝试读取一个将分别显示数字和字符的字符串。

附加信息:
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/

相关文章:

C++迭代器停留在第一个值

c++ - 终止 protected 防病毒进程

regex - 如何判断正则表达式中的匹配项之间是否存在三个或更多字符?

c++ - 如何找出具有文件路径的字符串中是否有任何非ASCII字符

java - 在Java中为字符串添加前缀?

c++ - 如何使用 Boost Program Options 提取已解析选项的序列?

c++ - 如何从按值返回的函数初始化 std::shared_ptr?

C++11 线程不适用于虚拟成员函数

c++ - 将字符串分配给 char 数组的列

java 字符串到对象