gpt4 book ai didi

c++ - stoi "terminate called after throwing an instance of ' std::无效参数'

转载 作者:搜寻专家 更新时间:2023-10-31 02:19:10 27 4
gpt4 key购买 nike

我目前正在研究一个动态编程问题,我决定用 C++ 而不是我常用的 Java/C# 来编写它来提高我的技能。但是,我收到一个我无法弄清楚的错误。编辑:我将在这里发布我的整个解决方案:

int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int linecounter = 0;
int value = -1;
int differentCoins = -1;
int uniqueCoinCount = -1;
std::vector<std::vector<int>> array;
int *uniqueCoins;
int totalAmount = -1;

for (std::string line; std::getline(std::cin, line); ) {
if (linecounter % 2 == 0) {
string inputs[2];
int i = 0;
stringstream ssin(line);
while (ssin.good() && i < 2){
ssin >> inputs[i];
++i;
}
cout << inputs[0];
cout << inputs[1];
totalAmount = std::stoi(inputs[0]);
uniqueCoinCount = std::stoi(inputs[1]);
uniqueCoins = new int[uniqueCoinCount + 1];

}
if (linecounter % 2 == 1) {
array.resize(uniqueCoinCount + 1, std::vector<int>(totalAmount + 1));
for (int i = 0; i < totalAmount; i++) {
array[i][0] = 0;
}
for (int i = 0; i <= uniqueCoinCount; i++) {
array[0][i] = 1;
}


stringstream ssin(line);
int coinCounter = 0;
uniqueCoins[coinCounter] = 0;
coinCounter++;
while (ssin.good() && coinCounter < uniqueCoinCount + 1){

ssin >> uniqueCoins[coinCounter];
coinCounter++;
}

for (int i = 1; i < totalAmount; i++) {
for (int j = 1; j <= uniqueCoinCount; j++) {
int totalExcludingCoin = array[i][j - 1];
if (uniqueCoins[j] <= i) {
array[i][j] = totalExcludingCoin + array[i - uniqueCoins[j]][j];
}
else {
array[i][j] = totalExcludingCoin;
}
}
}
}
linecounter++;
}

//cout << array[totalAmount][uniqueCoinCount + 1];
}

当我使用 cout << inputs[0] 时, 我可以看到它打印出 4 .然而,hackerrank 编译器给我一个错误提示

"terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi"

可能是什么问题?我也试过 atoi() ,返回我 40而不是 4 ,可能是由于 atoi返回 0什么时候出错?是因为它读取了空终止符还是什么?

谢谢

这是 hackerrank 上的输出:

Nice try, but you did not pass this test case.Input (stdin)4 31 2 3 Your Output (stdout)43Expected Output4Compiler MessageAbort CalledError (stderr)terminate called after throwing an instance of 'std::invalid_argument'  what():  stoi

最佳答案

        while (ssin.good() && i < 2){
ssin >> inputs[i];
++i;
}

您正在使用状态报告功能来预测 future 。 good 函数不会告诉您 future 操作的结果是什么,只会告诉您过去操作的结果。您需要实际检查操作 (ssin >> inputs[i]) 是否成功,而不是假设如果流在过去是好的,它就一定会成功。

关于c++ - stoi "terminate called after throwing an instance of ' std::无效参数',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33841725/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com