Hi I am relatively new beginner. I am trying to write a function that outputs the first and last digits of a number and also the total number digits of a number(the number is inputted by the user). The program works on its own, but when I try to make it a function it compiles and then I get a really weird error.
This is what I have written as my function:
#include<iostream>
#include<string>
using namespace std;
void order(string str)
{ int d =0;
int e;
string f;
string l;
for (d; d<str.length(); d++)
{string ch= str.substr(d,1);
string f = str.substr(0,1);
e = d-1;
string l = str.substr(e,1);
}
cout << "The first digit is "<< f << ". The last digit is "<< l << ".
The total number of digits is "<< d<< endl;
}
int main()
{ int d; //total number of digits
string str;
cout << "Please enter a number." << endl;
cin >> str;
order(str);
return 0;
}
And the error message I get when I input a number is:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr
Aborted
If anyone can help me correct the error that would be great!
Code tags and indentation would make the code more legible.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
void order(string str)
{
int d =0;
int e;
string f;
string l;
for (d; d<str.length(); d++)
{
string ch= str.substr(d,1);
string f = str.substr(0,1);
e = d-1;
string l = str.substr(e,1);
}
cout << "The first digit is "<< f << ". The last digit is "<< l
<< ". The total number of digits is "<< d<< endl;
}
On line 12, d is 0, e is -1 and so you have: str.substr(-1,1); which is not good :)
void order(string str)
{
if (str.length() < 1) return; // protect against invalid memory access.
cout << "The first digit is " << str.at(0);
cout << ". The last digit is " << str.at( str.length() - 1 );
cout << ". The total number of digits is " << str.length() << endl;
}