如何只计算字符串中的整数
How to count only integers in a string
我有这一小段代码,我试图工作在一个字符串中,并为字符串中的每个数字添加一个由空格分隔的计数器。但是,如果它遇到非整数,它会立即停止计数器,这不是我想让它做的。
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int counter;
int main()
{
cout << "Please input string: ";
string input;
getline(cin, input);
istringstream ss(input);
int num;
while(ss >> num)
{
counter++;
}
cout << "Amount of integers in string: " << counter << endl;
}
例如,如果我输入字符串3 4 5
,它将正确地返回字符串中的3个整数,但如果我输入3 4 x 6 t 8
之类的东西,它会说我在字符串中只有两个整数。
如何解决这个问题?
ss >> num
一旦遇到非整数,将使流进入错误状态,使while (ss >> num)
终止流。
像许多其他问题一样,这可以通过引入某种程度的间接来解决。
在这种情况下,您可以通过第二个流间接使用:
istringstream ss(input);
string word;
while (ss >> word)
{
istringstream maybenumber(word);
int number = 0;
if (maybenumber >> number)
{
counter++;
}
}
operator>>
返回一个转换为bool的流,表示是否设置了任何错误标志;这就是在while循环中使用的。如果流中读位置的字符序列不是int,则设置失败位,并在循环中将流转换为false
,结束程序。
你可能想要检查循环中的那个位。如果它是失败位(而不是eof),则清除它,读入整数之间的字符串,并继续循环。
你们的规格不是很精确;上面描述的算法将为字符串"123 abx2"返回1。如果你想在这里返回2或4,你必须在单个字符级别检查数据
您需要首先检查读取的输入值是否为数字后加空格或字母,然后增加计数器。一个可能的实现如下所示
int main()
{
cout << "Please input string: ";
string input;
getline(cin, input);
int counter = 0;
if(input.size() == 1 && isdigit(input[0])){
counter ++;
}else{
for(int i = 1; i < input.size(); ++i){
// works for all but the last element
if(isdigit(input[i-1]) && (isspace(input[i]) || isalpha(input[i]))) counter++;
}
// check the last element
if(isdigit(input[input.size()-1])) counter ++;
}
cout << "Amount of integers in string: " << counter << endl;
}
注意:
以上代码甚至考虑整数在非整数字符中的字符串,例如:5dkjfkd
使用isdigit:
std::string str = "4 a h a 1 23";
size_t countNumbers(0);
for ( size_t i = 0; i < str.size(); i++ )
{
if( isdigit(str[i]) && ( i == 0 || isspace(str[i-1]) ) )
{ countNumbers++; }
}
std::cout << "There are " << countNumbers << " numbers" <<
" in the string "" << str << ""." << std::endl;
在while条件中,您应该检查字符串的结尾,而不是数字。然后,检查它是否是一个要增加计数器的数字。
当遇到非整数时,while
条件计算为false。要纠正这个问题,循环到字符串的末尾,并且只在遇到整数时增加counter。
有点像,
bool checknum (string x)
{
for (auto &i: x) if (!isdigit(i)) return false;
return true;
}
string num;
while (!ss.eof())
{
getline (ss, num, ' ');
if (checknum(num)) counter++;
}
相关文章:
- C 字符串返回字符串的整数/双精度/长整型值
- 尝试将字符串/字符转换为整数会产生意外结果
- 从字符串中提取整数并形成一个数组
- 如何将整数字符串转换为整数的二维向量?
- 如何初始化整数+字符串数组
- 将字节数组转换为逗号分隔的整数字符串
- 编写 LLVM 整数/字符串输入
- 使用户输入整数字符串,然后输出不同的字符串
- 如何在 python 中将无符号字符类型的整数字符串转换为整数
- 将整数字符串转换为整数的最简单方法
- 如何检查输入是否为整数/字符串
- 如何将二进制字符串转换为整数字符串
- 将二进制字符串转换为整数字符串c++
- 如何在c++中将一个整数字符串转换为数组
- 整数字符串压缩算法
- 当 0 是行中的最后一个整数时,如何使用 c++ 检测您已经到达整数字符串的末尾?
- 将整数字符串解析为 std 向量
- 用空格分割一个正/负整数字符串
- 我如何在c++中排序一个整数字符串
- 添加整数字符串