0

Not getting the meaning of error

#include <iostream> #include <string> using namespace std; class Binary { string s; public: void read(void) { cout << "Enter a binary number "; cin >> s; } void chck_binary() { for (int i = 0; i <= s.length(); i++) { if (s.at(i) != '0' && s.at(i) != '1') { cout << "Incorrect Binary Format" << endl; exit(0); } } } void ones(void) { for (int i = 0; i <= s.length(); i++) { if (s.at(i) == '0') { s.at(i) = '1'; } else { s.at(i) = '0'; } } } void display(void) { for (int i = 0; i <= s.length(); i++) { cout << s.at(i) << endl; } } }; int main() { Binary s; s.read(); s.chck_binary(); s.ones(); s.display(); return 0; } Error Enter a binary number 1000 terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::at: __n (which is 4) >= this->size() (which is 4) What is wrong ?? How to solve the error ?? What is the meaning of the error??

10th Feb 2023, 2:19 PM
Sabnis Ashutosh
Sabnis Ashutosh - avatar
5 Answers
+ 4
The error you're encountering is caused by the line s.at(i) in the functions chck_binary, ones, and display. s.at(i) is a method to access the i-th character of the string s. However, in C++, arrays and strings are indexed starting from 0, so the last valid index of a string of length n is n-1. But in the code, the loop in the functions goes up to i <= s.length(), which means that the loop will try to access an index that is one greater than the last valid index of the string, resulting in an std::out_of_range exception. To solve this error, you should change the comparison in the loop condition to i < s.length(): for (int i = 0; i < s.length(); i++) { // ... } This way, the loop will never try to access an invalid index.
10th Feb 2023, 3:41 PM
Sadaam Linux
Sadaam Linux - avatar
+ 2
Error meaning that you are trying to use "out of range" for string index.. Use < just, instead of <= in loop condition. Try this way, in all loops: for(size_t i = 0; i < s.length(); i++){
10th Feb 2023, 2:53 PM
Jayakrishna 🇼🇳
0
What are u creating in c++
10th Feb 2023, 2:31 PM
Shubham Dadpe
Shubham Dadpe - avatar
0
I can create u a code
10th Feb 2023, 2:31 PM
Shubham Dadpe
Shubham Dadpe - avatar
0
If possible
10th Feb 2023, 2:31 PM
Shubham Dadpe
Shubham Dadpe - avatar