简体   繁体   中英

I'm getting an error that the debug assertion failed?

I am trying to read in a string from the user, change it to an int array and then display it int by int. This is so I can get very large int numbers, but when I run it, it lets me enter a number, but then it gives me an error that the debug assertion failed and that I should abort, retry, or ignore. There is an invalid null pointer. I don't know what means. Here is what I have:

  //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;
}
int length1 = number1.length();

Is going to set length1 to the size of the string. Then in the first iteration of

for (int i = length1; i >= 0; i--) {
    numberOne[k] = number1[i] - 48;
    k--;
}

You are accessing number1[i] with i = length1 and since string positions are 0 based you are accessing on past the end of the string. This is undefined behavior and in this case an assertion is being thrown. To fix this you need to set i to length1 - 1 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM