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

The iterator is supposed to read an entire number, but it only reads the first digit

本文关键字:数字 读取 第一位 迭代器      更新时间:2023-10-16

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

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

将这些字符收集到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;

没有必要使用您的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;
}

引用:

  • isdigit
  • ostringstream