如何只计算字符串中的整数

How to count only integers in a string

本文关键字:整数 字符串 计算      更新时间:2023-10-16

我有这一小段代码,我试图工作在一个字符串中,并为字符串中的每个数字添加一个由空格分隔的计数器。但是,如果它遇到非整数,它会立即停止计数器,这不是我想让它做的。

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