我试图从用户读取一个字符串,将其更改为一个int数组,然后通过int显示它。这样我可以获得非常大的int数,但是当我运行它时,它允许我输入一个数字,但是它会给我一个错误,调试断言失败并且我应该中止,重试或忽略。有一个无效的空指针。我不知道是什么意思。这就是我所拥有的:
//LargeInt.h File
#pragma once
#include <iostream>
#include <string>
using namespace std;
class LargeInt
{
private:
string number1;
string number2;
string sum;
public:
LargeInt();
~LargeInt();
//This function will take the
//the number entered by user
//as int digits and print out
//each digit.
void ReadNumber(int[]);
};
//LargeInt.cpp file
#include "stdafx.h"
#include "LargeInt.h"
#include <iostream>
LargeInt::LargeInt() {
number1 = " ";
}
LargeInt::~LargeInt() {
}
//This function will take the
//the number entered by user
//as int digits and print out
//each digit.
void LargeInt::ReadNumber(int
number[]) {
for (int i = 0; i < 75; i++) {
cout << number[i]; }
}
//Main File
#include "stdafx.h"
#include <string>
#include "LargeInt.h"
#include <iostream>
using namespace std;
int main()
{
string number1 = " ";
string number2 = " ";
string sum = " ";
int summ[75];
//Get number 1 from user and output it
int numberOne[76] = {};
cout << "Enter first number: ";
getline(cin, number1);
cout << endl;
//Check to see if it is more than 75 digits
if (number1.length() > 75) {
cout << "Invalid number!" << endl;
}
else {
int length1 = number1.length();
cout << "First Number: " << endl;
int k = 75;
for (int i = length1; i >= 0; i--) {
numberOne[k] = number1[i] - 48;
k--;
}
}
LargeInt num1;
num1.ReadNumber(numberOne);
cout << endl;
system("pause");
return 0;
}
答案 0 :(得分:3)
int length1 = number1.length();
是否将length1
设置为字符串的大小。然后在
for (int i = length1; i >= 0; i--) {
numberOne[k] = number1[i] - 48;
k--;
}
您正在使用number1[i]
访问i = length1
,因为字符串位置为0,您将在字符串末尾访问。这是未定义的行为,在这种情况下会抛出一个断言。要解决此问题,您需要将i
设置为length1 - 1
。