为什么 std::stoi() 返回异常?

问题描述 投票:0回答:1

你好, 我一直在尝试使用 C++ 解决以下问题:https://www.codewars.com/kata/554b4ac871d6813a03000035/train/cpp

使用以下代码:

// Solution
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

string highAndLow(const string &numbers)
{
  // If the string passed as function argument is empty, the function returns an empty string.
  if (numbers.empty())
  {
    return "";
  }
  else
  {
    vector <int> nums = {};
    string numbers_ = numbers;
    while (numbers_.find(' ') != string :: npos)
    {
      nums.push_back(stoi(numbers_.substr(0, numbers.find(' '))));
      numbers_.erase(0, numbers_.find(' ') + 1);
    }
    
    nums.push_back(stoi(numbers_));
    
    sort(nums.begin(), nums.end());
    
    return to_string(nums.back()) + " " + to_string(nums.front());
  }
}

测试上面的代码时,它会返回

std::exception, what(): stoi
来调用
highAndLow("8 3 -5 42 -1 0 0 -9 4 7 4 -4")

虽然对于

highAndLow("1 2 3")
来说效果很好。

我认为这与负号有关

-
,但在我自己编写了一些带有负数的测试用例后,情况似乎并非如此。

c++ string exception
1个回答
0
投票

当你到达 while 循环的这一行时,会抛出错误:

      nums.push_back(stoi(numbers_.substr(0, numbers.find(' '))));

当变量数字具有此值时:

"-5 42 -1 0 0 -9 4 7 4 -4"

它在找到的第一个负数处被阻止。

要使其正常工作,请从

numbers_.substr(0, numbers.find(' '))

中删除“0”

所以你在第一个 while 循环中的行将是:

nums.push_back(stoi(numbers_.substr(numbers.find(' '))));

然后你的程序将正确执行。

© www.soinside.com 2019 - 2024. All rights reserved.