【发布时间】:2021-06-05 04:58:03
【问题描述】:
我不确定我的代码有什么问题。在我尝试使用 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';
}
}
代码的重点是接受用户的命令行输入并用单词拼出数字。
【问题讨论】:
-
任何时候您使用
argv而不先检查argc来确认它是安全的,您就是在自找麻烦。argv:参数列表。argc: 列表中的参数数量。 -
在引用 argv[1] 之前需要检查 argc。如果没有提供引用 argv[1] 的 arg,则将是未定义的,例如 segfault。
-
我可以想象如果这个条件 ** while (s != "quit") {nums.push_back(s);} ** 没有得到错误,可能是无限循环?
-
@KenWhite 你为什么这么认为?不是 operator== 标准的一部分,它返回 lhs.compare(rhs) == 0?
-
@OP 哪一行代码发生了分段错误? -- 请让我知道你的想法。 -- 你应该这样做。解决问题是一回事,但至少,您应该努力调试代码以找出问题的哪里。 How to debug small programs
标签: c++ segmentation-fault argv