I am not sure what the problem is with my code. It was all working until I tried to use the argv command and then when I went to execute i get a segmentation fault. please let me know your thougths.
#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';
}
}
the point of the code is to take in the users command line input and the spell out the number in words.
i think the problem is in potentially infinite loop while (s.= "quit"){nums;push_back(s);}
, what if s is really not quit ?. infinite loops are more than likely to cause segmentation faults.
warning: at the line int a = stoi(s);
you'll have terminate called after throwing an instance of 'std::invalid_argument' what(): stoi
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.