我正在尝试使用 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/