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

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.

Related

I'm having issues with my for_each function and my finding prime function right now

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template <typename t>
void find_prime(const vector<t>& V)
{
int num;
bool is_prime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
cout << "This is the prime number: " << num << endl;
}
else {
cout << "This number is not a prime number: " << num << endl;
}
}
int main() {
int input;
vector<int> num;
cout << "please enter a number larger than 1: ";
cin >> input;
for (int i = 0; i < input; i++) {
cout << i << endl;
}
num.push_back(input);
for_each(num.begin(), num.end(), find_prime<int>);
}
Right now I'm writing currently doing a project that has a user populate the arry with a singular number, and then display all the numbers from 2 up to the number the user entered. After doing so it should then step through the vector and pass each element of the array through the find_prime function. Though I do not know why my program is deciding it wants to start crashing.
This is a simpler implementation of your code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
std::string find_prime(int num) {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return "This number is not a prime number: ";
}
}
return "This is a prime number: ";
}
int main() {
int input;
cout << "please enter a number larger than 1: ";
cin >> input;
for (int i = 2; i <= input; i++) {
cout << find_prime(i) << i << endl;
}
}
The above code takes in a number, and then for every number starting from 2 up to the number entered, the computer prints "This is a prime number: " <num> for primes and "This number is not a prime number: " <num> for non-primes.
Here, I have removed the usage of templates because that's completely unnecessary. For the same, I have also removed the vector you created. But in case you need all of that, you can use the below code, but I strongly advise the code provided earlier:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template <typename t>
std::string find_prime(t num) {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return "This number is not a prime number: ";
}
}
return "This is the prime number: ";
}
int main() {
int input;
vector<int> nums;
cout << "please enter a number larger than 1: ";
cin >> input;
for (int i = 2; i <= input; i++) {
nums.push_back(i);
}
for (auto& i : nums) {
cout << find_prime(i) << i << endl;
}
}

C++ rand() not working with string array

I'm creating a small program that allows the user to input 3 names (or whatever string they want). The program should then display all three strings (which is working), then it should use the rand() function to randomly display one of the three strings. This is the part that isn't functioning properly.
#include <iostream>
#include <string>
using namespace std;
void display(string[], int);
const int SIZE = 3;
int main()
{
string names[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << ": ";
getline(cin, names[i]);
}
cout << endl;
display(names, SIZE);
int name = rand() % (2 + 1 - 0) + 0;
cout << names[name];
cin.get();
return 0;
}
void display(string nm[], int n)
{
int i = 0;
for (i; i < n; i++)
{
cout << "Name " << i + 1 << ": ";
cout << nm[i] << endl;
}
}
I had it set up differently before, and it gave me an error, but after changing it to what it is now, it always gives me the last element [2].
Is this a code error, or is it just that rand() always gives the same output on the same system?
After some discussion in the comments, it became apparent that the issue was that I was not seeding the rand() function. Below is part of the code that was not functioning, corrected.
(Also, as a sidenote, to use the time() function, <ctime> or <time.h> has to be included.)
srand(time(NULL));
int name = rand() % 3;
cout << names[name];
(Thanks to #manni66 for pointing out that it was useless to include an overly complicated calculation to get the range for rand(), as it just had to be a single integer.
seeding with current time works :
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cstdio>
using namespace std;
void display(string[], int);
const int SIZE = 3;
int main()
{
string names[SIZE];
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << ": ";
getline(cin, names[i]);
}
cout << endl;
display(names, SIZE);
srand(time(NULL)); // use current time as seed for random generator
int name = rand() % 3 ;
printf(" random %i \n", name);
cout << names[name];
cin.get();
return 0;
}
void display(string nm[], int n)
{
int i = 0;
for (i; i < n; i++)
{
cout << "Name " << i + 1 << ": ";
cout << nm[i] << endl;
}
}

How do I print an array, pause it and continue to print the array in c++?

How do I display 3 names at a time, pausing to let the user press a key before the list continues displaying.
My code now only loops the first 3 values of the array
#include <iostream>
#include <string>
#include <iomanip>
using std::setw;
using namespace std;
int main() {
string a;
string names[10]; //size of array
for (int i = 0; i < 10; i++)
{
std::cout << "Enter name ";
std::cin >> a; //user input
names[i] = a; //assigns input to array
}
cout << "\n";
for (int k = 0; k < 10; k++)
{
for (int j = 0; j < 3; j++)
{
cout << names[j] << endl;
}
system("pause");
}
}
I changed the answer based on your comment. Instead of sleeping we just pause and wait until user inputs anything into the keyboard. Also a note, since you're using namespace, you don't need to include std::, I decided to use it since I was unsure what way you wanted.
#include <iostream>
#include <string>
#include <iomanip>
using std::setw;
using namespace std;
int main() {
string a;
int pauseCheck = 0; //new var
string names[10]; //size of array
for (int i = 0; i < 10; i++) {
std::cout << "Enter name ";
std::cin >> a; //user input
names[i] = a; //assigns input to array
}
cout << "\n";
for (int k = 0; k < 10; k++) {
cout << names[k] << endl;
pauseCheck++; //increments check
if (pauseCheck == 3) { //if equals 3
system("pause"); //we pause till user input
pauseCheck = 0; //reset pause check
}
}
system("pause"); //last and final pause before program ends
}
Here's another way of doing it which I think is a little more straight forward:
#include <iostream>
#include <string>
#include <iomanip>
using std::setw;
using namespace std;
int main() {
string a;
string names[10]; //size of array
for (int i = 0; i < 10; i++)
{
std::cout << "Enter name ";
std::cin >> a; //user input
names[i] = a; //assigns input to array
}
cout << "\n";
for (int k = 0; k < 10; k++)
{
cout << names[k] << endl;
if((k + 1) % 3 == 0) // everytime k + 1 is divisible by 3, let user hit a key
system("pause");
}
}
You can wait for a Enter-Press with another std::cin, just write into an garbage value.
I think other ways are not platform independent. You could ofcourse use the windows api, or unix stuff to get a key press.

C++ convert string array to integers, then sum int array

I need to pass an user input integer to a sumTotal(& userInt) function.
If the int is 2341 I need to sum 2+3+4+1 = 10 and return the value to main!
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// The program needs to input an integer like 2341, then sum it as 2+3+4+1 + 10
// I am in putting an integer and will pass it to a funtion by &.
int main()
{
string strNumber;
int intNumber = 0;
cout << "Enter your number: ";
cin >> intNumber;
// programming the logic for sumTotal(& intNumber) function before creating
strNumber = to_string(intNumber);
cout << "Your number is: " << strNumber << endl;
cout << "Your numbers length: " << strNumber.length() << " digits" << endl;
// here I need to convert the string array to an integer array
for (int i = 0; i < strNumber.length(); ++i){
intNumber[&i] = strNumber[i] - '0';
cout << "Element [" << i << "] contains: " << strNumber[i] << endl;
}
// next a recursive function must sum the integer array
// I am taking an online course and cant afford a tutor please help!
system("pause");
return 0;
}
if you want recursion ,you don't need any string work,try this :
#include <iostream>
using namespace std;
int recSum(int);
int main(){
int i;
cin>>i;
cout<<recSum(i);
return 0;
}
int recSum(int i){
return i==0?0:i%10+recSum(i/10);
}
recursion on array version
#include <iostream>
using namespace std;
int recSum(int* ary,int len){
return len<0?0:ary[len]+recSum(ary,len-1);
}
int main(){
int j[]={1,2,3,4,5,6,7,8,9,10};
cout<<recSum(j,9);
}
A simple and efficient method is to keep the number as a string and access the digits one at a time.
Note the equation:
digit_number = digit_character - '0';
Also, knowing that when summing digits, the order is irrelevant. So, we have:
sum = 0;
for (i = 0; i < string.length(); ++i)
{
sum += string[i] - '0';
}
A string is an array of chars. To convert a char to an int you have to do 'char' - '0'.
I wrote a couple of versions.
Pick whichever one you like best.
#include <iostream>
#include <string>
int main()
{
std::string str = "1234";
int sum = 0;
//pre C++11
for (std::string::iterator i = str.begin(); i != str.end(); ++i)
sum += (*i - '0');
//C++11
sum = 0;
for (auto i = str.begin(); i != str.end(); ++i)
sum += (*i - '0');
//ranged-for
sum = 0;
for (const auto &i : str)
sum += (i - '0');
std::cout << "Sum: " << sum;
std::cin.get();
}

Array and function c++

I built a program that accepts two input from the user, using a array inside a loop, it is passed to a function inside a class which will display the two number.
The problem is when the user is inputting a number and it is 1. The program continuously asks the user to input a number, and when 2 is entered the program ask another number and end, but for example you entered 2 and 3. . . it will then output 2 and 4 (so 3 + 1 ) and always the last number is plus one. Here is the code:
main.cpp:
#include <iostream>
#include "newclass.h"
using namespace std;
int main()
{
int array_variable_main[2];
for(int counter = 1; counter <= 2; counter=counter+1)
{
cout << "Enter a Number: " << endl;
cin >> array_variable_main[counter];
}
newclass sum_object;
sum_object.loop_function(array_variable_main, 2);
return 0;
}
newclass.cpp:
#include "newclass.h"
#include <iostream>
using namespace std;
newclass::newclass()
{
}
void newclass::loop_function(int array_variable[], int arraysize)
{
cout << "The numbers that are stored in the array are: " << endl;
for(int counter = 1; counter <= arraysize; counter = counter+1)
{
cout << array_variable[counter] << endl;
}
}
newclass.h:
#ifndef NEWCLASS_H
#define NEWCLASS_H
class newclass
{
public:
newclass();
void loop_function(int array_variable[], int arraysize);
};
#endif // NEWCLASS_H
You have to remember that array indices go from zero to size-1. So for your array it's zero and one. Anything beyond that leads to undefined behavior. Undefined behavior can't easily be predicted, so the result of your program could be anything.
In C and C++ array index normally starts at 0 so this
int array_variable_main[2];
for(int counter = 1; counter <= 2; counter=counter+1)
{
cout << "Enter a Number: " << endl;
cin >> array_variable_main[counter];
}
will access outside the array
do instead
int array_variable_main[2];
for(int counter = 0; counter < 2; ++counter)
{
cout << "Enter a Number: " << endl;
cin >> array_variable_main[counter];
}