Reputation: 75
So the problem is that when I run this code compiler ask me to enter value when I enter value and hit enter an error pop saying abort() has been called. Here is my code. how can I remove this error?
#include <iostream>
#include<string>
using namespace std;
class binary
{
private:
string num;
public:
void display();
void chkBin();
};
void binary::chkBin()
{
int x=0;
for (int i = 0; i <= num.length(); i++)
{
if (num.at(i) != '0' && num.at(i) != '1')
{
x = -1;
}
}
if (x==-1)
{
cout << "The number is not binary";
}
else if (x==1)
{
cout << "The number is binary";
}
}
void binary::display()
{
cout << "Enter a number"<<endl;
cin >> num;
}
int main()
{
binary b;
b.display();
b.chkBin();
return 0;
}
Upvotes: 1
Views: 2628
Reputation: 118097
The loop condition i <= num.length()
is what makes your program throw std::out_of_range
(and then abort
). That's because num[num.length()]
is out of bounds. You can only access num[0]
to num[num.length() - 1]
(inclusive) so the loop condition should have been i < num.length()
.
Also, int x=0;
should probably be int x=1;
for it to be able to print The number is binary
.
When you want to go through the whole range, you can (since C++11) use a range-based for loop instead which makes it easier to avoid mistakes like this.
Example:
void binary::chkBin()
{
for (auto ch : num) // a range-based for loop
{
if (ch != '0' && ch != '1')
{
std::cout << "The number is not binary\n";
return;
}
}
std::cout << "The number is binary\n";
}
Upvotes: 1