为什么我的C++基转换器中出现分段错误?
Why do I get a Segmentation Error in my C++ Base Converter?
我是 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) {
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?