| miller18 (5) | |
|
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! | |
|
|
|
| Fransje (178) | |||
It gave me very strange errors too, so here is the corrected, working version:
| |||
|
|
|||
| Chervil (812) | |||
Code tags and indentation would make the code more legible.
On line 12, d is 0, e is -1 and so you have: str.substr(-1,1); which is not good :)Do you actually need a for loop? | |||
|
Last edited on
|
|||
| Stewbond (1672) | |||
I think your function can be simplified:
| |||
|
Last edited on
|
|||
| Fransje (178) | |
| oh wait, I thought total number was the sum of all the digits in the number :) | |
|
|
|