迭代器应该读取整个数字,但它只读取第一个数字

时间:2011-07-14 18:56:16

标签: c++

我编写了这段代码,用字符串迭代器从字符串中提取数字。 迭代器获取第一个数字并决定每天调用它。 为什么会这样?

    #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;

2 个答案:

答案 0 :(得分:1)

只需将字符收集到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;

答案 1 :(得分:1)

无需使用stringstream convertToString。并且你没有完全正确地使用它,所以这就是你的问题潜入的地方。由于我们只处理字符而没有实际数字,你可以把它全部保存为字符串:

int main()
{
  std::string myAge = "I am 23 years old";
  std::ostringstream digits;

  for(std::string::const_iterator iterator = myAge.begin();
      iterator != myAge.end();
      ++iterator)
  {
      const char numberInCharacterForm = *iterator;
      if(isdigit(numberInCharacterForm))
      {
         digits << numberInCharacterForm;
      }
  }

  std::cout << digits.str() <<endl;   
  getch();
  return 0;
}

参考文献: