迭代器应该读取整个数字,但它只读取第一位数字
The iterator is supposed to read an entire number, but it only reads the first digit
我编写了这段代码,使用字符串迭代器从字符串中提取数字。迭代器取出第一个数字,并决定收工。为什么会这样呢?
#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
相关文章:
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 从.txt文件中读取浮点型数字并在公式中使用它们
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 为什么我的程序在读取/写入文件时会删除最重要的数字?
- C++:从文件中读取字符串和整数,并获得最大数字
- 如何读取具有数字间隔的文本文件?C++
- 如何将uint8_t的二进制表示形式读取为数字
- C++ - 将 int 读取为字母和数字序列
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- 我可以从具有不同数字分隔符的istream中读取双值吗
- 如何从文件中读取用空格分隔的数字
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 将任意大小的大量 Base-10 数字读取到位集中
- 无需使用循环,就将ISBN-10的前9位数字读取为字符串并计算第10位数字
- 将字符串和数字读取到向量C
- C++ 将文件中的数字读取到数组中,然后将其打印到其他数组中
- 将数字读取到矢量
- (c++)试图将数字读取到数组中,在输出中得到垃圾数字
- 在读取文件时,在增加数组大小的同时,将浮点数字读取到动态分配的中
- 猜数字 - 读取错误时无限循环