c++ - 使用 argv 的分段错误
问题描述
我不确定我的代码有什么问题。在我尝试使用 argv 命令之前,一切正常,然后当我去执行时,我遇到了分段错误。请让我知道你的想法。
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int main(int argc, char **argv) {
vector<string> nums;
vector<string> single {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
vector<string> second {"eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
vector<string> twos {"twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"};
string num;
string s;
s = argv[1];
while (s != "quit") {
nums.push_back(s);
}
int b =s.length();
int a = stoi(s);
if (a< 10){
cout << "Number" << s << "is written as" << single[a] << '\n';
}
else if (a < 100){
int temp10 = a / 10;
int temp1 = a - temp10*10;
if (temp1 == 0){
cout << "Oops! Entered a 0 in the number";
}else{
cout << "Number" << s << "is written as" << single[temp10] << single[temp1] << '\n';
}
}
else if (b == 3){
int temp100 = a / 100;
int temp10 = a - temp100*100;
temp10 = temp10 / 10;
int temp1 = a - temp100*100 - temp10*10;
if (temp10 == 1){
cout << "Oops! Entered a 1 in the tens place";
}else if (temp10 == 0 || temp1 == 0){
cout << "Oops! Entered a 0 in the number";
}else{
cout << "Number" << s << "is written as" << single[temp10] << single[temp1] << '\n';
}
}
else if (b == 4){
int temp1000 = a / 1000;
int temp100 = a - temp1000*1000;
temp100 = temp100 / 100;
int temp10 = a - temp1000*1000 - temp100*100;
temp10 = temp10 / 10;
int temp1 = a - temp1000*1000 - temp100*100 - temp10*10;
if (temp10 == 1){
cout << "Oops! Entered a 1 in the tens place";
}else if (temp1000 == 0 || temp100 == 0 || temp10 == 0 || temp1 == 0){
cout << "Oops! Entered a 0 in the number";
}else{
cout << "Number" << s << "is written as" << temp1000 << "thousand" << temp100 << "hundred" << single[temp10] << si
ngle[temp1] << '\n';
}
}
代码的重点是接受用户的命令行输入并用单词拼出数字。
解决方案
我认为问题在于潜在的无限循环while (s != "quit"){nums.push_back(s);}
,如果s真的没有退出怎么办?无限循环很可能导致分段错误。
警告:在抛出 'std::invalid_argument' what(): stoi 的实例后,int a = stoi(s);
您将终止调用
推荐阅读
- javascript - Jest 全局设置导致不一致的测试通过/失败
- ios - iOS 搜索栏与导航栏混淆
- python - 没有副作用类型注释的可迭代
- c++ - 'operator++(int) &' 运算符重载中的 '&' 是什么意思?
- flutter - 如何在扫描渐变中包含笔画帽?
- javascript - 如何使相同的按钮隐藏和显示块?
- php - 如何通过单击朋友的个人资料来更新消息状态以阅读
- android - 拔下电源后,React-Native Android 设备上不会发生振动
- sql - Scala Doobie PSQLException:错误:使用“Like %”时输入末尾的语法错误
- java - eclipse 在保存项目时自动编译。如何摆脱它