gpt4 book ai didi

c++ - 迭代器应该读取一个完整的数字,但它只读取第一个数字

转载 作者:行者123 更新时间:2023-11-30 04:33:36 25 4
gpt4 key购买 nike

我编写这段代码是为了使用字符串迭代器从字符串中提取数字。迭代器选取第一个数字并决定收工。为什么会这样?

    #include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
string myAge = "I am 23 years old";
string::iterator iterator;
char numberInCharacterForm;
string numberInStringForm;
stringstream convertToString;
for(iterator = myAge.begin();iterator!=myAge.end();iterator++)
{
numberInCharacterForm = *iterator;
if(numberInCharacterForm >= '0' & numberInCharacterForm <='9')
{
convertToString << numberInCharacterForm;
convertToString >> numberInStringForm;
}
}
cout << numberInStringForm <<endl;
getch();
return 0;
}

输出为2;

最佳答案

只需将字符收集到 stringstream 中,然后打印出来:

for(iterator = myAge.begin();iterator!=myAge.end();iterator++)
{
numberInCharacterForm = *iterator;
if(numberInCharacterForm >= '0' && numberInCharacterForm <='9') {
// note: && instead of & here ^
convertToString << numberInCharacterForm;
}
}
cout << convertToString.str() <<endl;

但是不需要对字符串进行手动迭代:

string myAge = "I am 23 years old"; 
string numberInStringForm;
std::remove_copy_if(myAge.begin(), myAge.end(),
std::back_inserter(numberInStringForm),
std::not1(std::ptr_fun(isdigit)));
std::cout << numberInStringForm << std::endl;

关于c++ - 迭代器应该读取一个完整的数字,但它只读取第一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6698485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com