为什么我的C++基转换器中出现分段错误?

Why do I get a Segmentation Error in my C++ Base Converter?

本文关键字:分段 错误 我的 C++ 转换器 为什么      更新时间:2023-10-16

我是 c++ 的学生,我们 3 周前就开始了。我们的任务是在不使用 stoi 或 atol 的情况下制作基本转换器。我们正在使用一个名为 Repl.it 的网站。我收到一个名为"分段错误"的错误,没有意义。它始于stringToDecmial。顺便说一下,我们指的是 ASCII 表。

#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
int strToDecimal(int base, string num);
string decimalToBase(int number, int base);
int main()
{
int menuChoice;
int startBase;
int numberInDecimal;
string number;
cout << "NUMBER BASE CONVERTER 2019" << endl;
cout << "By: Suraj Joshi" << endl << endl;
cout << "Enter number to convert: ";
cin >> number;
cout << "Choose your starting base: " << endl
<< "1. Binary" << endl
<< "2. Octal" << endl
<< "3. Decimal" << endl
<< "4. Hex" << endl;
cin >> menuChoice;
switch (menuChoice)
{
case 1: {
startBase = 2;
break;
}
case 2: {
startBase = 8;
break;
}
case 3: {
startBase = 10;
break;
}
case 4: {
startBase = 16;
break;
}
default: {
startBase = 0;
cout << "Invalid Choice..." << endl;
break;
}
}
numberInDecimal = strToDecimal(startBase, number);
cout << "Binary: " << decimalToBase(numberInDecimal, 2) << endl;
cout << "Decimal: " << numberInDecimal << endl;
cout << "Octal: " << decimalToBase(numberInDecimal, 8) << endl;
cout << "Hex: " << decimalToBase(numberInDecimal, 16) << endl;
return 0;
}
// This is where the problem starts(I Believe) I never experianced the problem
// when this wasnt here
int strToDecimal(int base, string num)
{
int sum = 0;
for (int i = 0; num.length() - 1; ++i) {
if (num[i] > 64)
sum += (num[i] - 55) * pow(base, num.length() - 1 - i);
else
sum += (num[i] - 48) * pow(base, num.length() - 1 - i);
}
return sum;
}
// this can be ingored, This isnt what is causing the problem but feel free to
// look at it, it isnt complete yet
string decimalToBase(int number, int base) {
int rem;
string tempStr(1, number % base + 48);
while (number != 0) {
rem = number % base;
number = number / base;
// str.insert(0, string(1, num % base + 48))
// or string tempStr (1, num % base + 48);
// str.insert(0, tempStr);
switch (rem) {}  // switch
}  // while
return " ";
}

分段错误是因为您正在读取num字符串的末尾。在您的strToDecimal功能中,此行

for (int i = 0; num.length() - 1; ++i) {

不执行正确的终止检查。只要num.length() - 1包含非零值,循环就会无限期地继续。您可能希望将其更改为:

for (int i = 0; i < num.length(); ++i) {