c++ - 使用 stringstream 从混合字符串中提取数字

标签 c++

我正在尝试使用 stringstream 从字符串中提取数字,例如 Hello1234。我编写了代码,该代码可用于在输入时与字符串分开,例如提取数字:

你好1234世界9876你好1234

给出1234 9876作为输出 但它不读取同时具有字符串和数字的混合字符串。我们怎样才能提取它呢? - 例如:Hello1234应该给出1234

这是我到目前为止的代码:

cout << "Welcome to the string stream program. " << endl;
    string string1;
    cout << "Enter a string with numbers and words: ";
    getline(cin, string1);

    stringstream ss; //intiazling string stream

    ss << string1;  //stores the string in stringstream 

    string temp;  //string for reading words
    int number;   //int for reading integers

    while(!ss.eof()) {
        ss >> temp;
        if (stringstream(temp) >> number) {
            cout << "A number found is: " << number << endl;
        }
    }

最佳答案

如果您不限于使用 std::stringstream 的解决方案,我建议您看看 regular expressions 。示例:

int main() {
    std::string s = "Hello 123 World 456 Hello789";    
    std::regex regex(R"(\d+)");   // matches a sequence of digits

    std::smatch match;
    while (std::regex_search(s, match, regex)) {
        std::cout << std::stoi(match.str()) << std::endl;
        s = match.suffix();
    }
}

输出:

123
456
789

关于c++ - 使用 stringstream 从混合字符串中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59066457/

相关文章:

c++ - C++ 有 move 和删除语义吗?

c++ - std::list 排序算法运行时

c++ - 调试时在lldb中获取类静态成员函数地址 : Interpreter couldn't resolve a value during execution

c++ - 画线不起作用,可能是什么问题?

c++ - make 文件中的 ".target-name"目标会始终运行吗?

c++ - 省略 C++ 模板参数列表时的区别

c++ - (C++) 如何验证 char 变量的用户输入?

c++ - 使用数组参数和非数组参数调用重载函数

c++ - 使用 g++ 从 g++ 和 gfortran 链接 .o 文件时出现 "__gfortran_pow_c8_i4"错误

c# - 有效地检查 List<List<int>> 中的数字是否仅以正数或负数存在