I am kinda new to programming and have never seen this kind of error, so if someone can help me it would be appreciated. I tried to use string for numbers to compare digits to one another, but got this error and I guess it doesn't work :D
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int n;
fstream f("telef.txt");
f >> n;
string numeriai;
for (int i=0; i<n; i )
{
f >> numeriai;
bool nice = false;
int length = numeriai.length();
for (int j=0; j<length; j )
{
char ch = numeriai.at(j);
char chh = numeriai.at(j 1);
if (ch > chh)
{
nice = true;
}
else
{
nice = false;
break;
}
}
if (nice = true)
{
cout << numeriai << endl;
}
for (int k=0; k<length; k )
{
char ch = numeriai.at(k);
char chh = numeriai.at(k 1);
if (ch == chh)
{
nice = true;
}
else
{
nice = false;
break;
}
}
if (nice = true)
{
cout << numeriai << endl;
}
}
}
CodePudding user response:
Let's assume you have a length of 10. That means your loop will loop until j = 9
for (int j=0; j<length; j )
At that point, what happens with the following?
char ch = numeriai.at(j);
char chh = numeriai.at(j 1);
ch
gets the value of the last character in the string (at index 9), but chh
tries to read one past the last character. This results in your out of range error.
You probably want to loop one less time to account for this:
for (int j = 0; j < length - 1; j )
Also note that
if (ch > chh)
{
nice = true;
}
else
{
nice = false;
break;
}
can be cleaned up to be
nice = ch > chh;
if(!nice) { break; }
CodePudding user response:
::at()
throws the exception and you are not handling it in the following call and similar ones:
char chh = numeriai.at(j 1);