Need help w/type conversion. (string to int)

I have this assignment for school and part of it involves this function below.

The function is supposed to convert a string to an int. (We can't use built in functions)

I think I am capable of testing the meet of the function on my own, but the problem I am having is that this isn't compiling because it fails to convert the string into an int.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  1 #include <iostream>
  2 #include <cstdlib>
  3 #include <cmath>
  4 #include <climits>
  5 #include <cstring>
  6 #include <string>
  7
  8 using namespace std;
  9
 10
 11
 12 int a_to_i(string input){
 13
 14    //Declarations
 15    string valid = input;
 16
 17    bool bad_input;
 18
 19 do{
 20
 21    bool bad_input = false;
 22
 23    for(int i = 0; i < valid.length(); i++){
 24
 25       if(valid[i] >= 48 && valid[i] <= 57 || valid[i] == 45){
 26
 27          cout << " Ding! " << endl;
 28       }
 29       else{
 30
 31         cout << "Please enter an integer: " << endl;
 32         bad_input == true;
 33
 34         cin >> valid;
 35         break;
 36
 37       }
 38    }
 39    }while(bad_input == true);
 40
 41
 42
 43
 44
 45 return valid; // Return as user_ans  in main
 46 }



The main function is below:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20


 59
 60 int main (){
 61
 62 string user_str;
 63 int user_ans;
 64
 65 // User types in answer to displayed equation:
 66 cout << "Type a string! \n\n";
 67
 68 cin >> user_str;
 69
 70 user_ans = a_to_i(user_str);
 71
 72 cout << user_ans << "Successfully returned to main function" << endl;
 73
 74 return 0;
 75 }
                                                     


The error report I get looks like this:

1
2
3
4
5
6

a_to_i.cpp: In function ‘int a_to_i(std::string)’:
a_to_i.cpp:45:8: error: cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘int’ in return
 return valid; // Return as user_ans  in main
        ^


Any help would be hugely appreciated.

Thank you a million in advance.

- Ash
closed account (E0p9LyTq)
You should use the <string> header template functions for converting a string to a numeric value. std::stoi for example:

http://www.cplusplus.com/reference/string/stoi/
Your compiler is not able to convert the 'valid' variable in the function to the return type int (I guess you could see that as well).

@FurryGuy he can't use built-in functions ;-;

Oh by the way why have you written || valid[i] == 45 inside the if condition? ASCII 45 is '-'.. and that's not an integer constant is it? 0_0

Are you sure they want you to convert the string into integer data-type or they just want you to filter out non-digits? Because if the function is not supposed to filter out '-' then you probably don't have to convert it to int because - is not an integer constant in the first place..


Here's the approach I had in mind: write the function as it is (except valid[i]==45) and then when you have gotten the value of valid, reverse the string 'valid'.

Now initialize a new integer variable to 0 (important).

And then follow this in the loop:
value (integer) = (value*10) + (valid[i] - '0') // where 'value' is the integer variable

That should work ^_^
If you need help with the code then we're always here! ;)

Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <sstream>
#include <string>
using namespace std;


//======================================================================


int stringToInt( string str )
{
   int i;
   string remainder;

   stringstream ss( str );
   if ( ss >> i && !( ss >> remainder ) )   // just an int and nothing else
   {
      return i;
   }
   else
   {
      cout << "Unable to return integer\n";
      return 0;
   }
}


//======================================================================


int main()
{
   string tests[] = { "123", "-456", "3.14159", "777 lucky!" };

   for ( string s : tests )
   {
      cout << "Test: " << s << '\n';
      cout << "Output: " << stringToInt( s ) << "\n\n";
   }
}


//====================================================================== 


Test: 123
Output: 123

Test: -456
Output: -456

Test: 3.14159
Unable to return integer
Output: 0

Test: 777 lucky!
Unable to return integer
Output: 0



Nwb wrote:
Because if the function is not supposed to filter out '-'

Not on its own, no, but it is how we indicate negative numbers.
Last edited on
Oh right totally forgot about negative numbers. And in that case you need to make sure that '-' can only appear at the beginning.

@lastchance's code is awesome for this if you're allowed to use stringstream.
@lastchance That looks great! I'm not familiar with stringstream, so I don't fully understand the code.
My assignment says that I can't use any built in string conversion functions. Would you say that stringstream converts a string in any way?


@Nwb I also don't know how to implement the code you suggested! lol. This is an intro class I'm taking. I don't know much.

Yes, I included the '-' for negative numbers. I'm not sure if that is the way to go, but I thought it made sense...
Last edited on
@ashwyn,
One feature that I really like about C++ is that all streams behave very similarly, whether they come from file, from the console or, in this instance, just a string of characters. Fundamentally, they all inherit from a common base.

In this instance, the stringstream is simply constructed from the contents of the original string on line 15, and thereafter behaves very much as if the input came from any other source. Its advantage here is that it copes appropriately with the possibility of the string being "ill-formed" in some way - even as simple as having blanks at beginning or end. I can't say whether or not this meets the terms of your assignment. However, otherwise your problem would be extremely complicated and would only be realistic for an intro class if you could assume that the string was only made up of digits and possibly an initial minus, when you could simply pick the digits off as an appropriate power of 10. So it really depends what assumptions you are allowed to make about your initial string.

A longer route is to first strip any blanks from start and end of the string and then iterate through it (you could work either forward or backward). The string gives an integer iff all characters are digits (you can test that with isdigit() rather than ASCII codes), apart from the possibility that the first character is a minus sign (just compare it with '-'). Even then you run the risk of overflowing the maximum range of an int or a long long.
Last edited on
@lastchance

You've been extremely helpful.
Thank you very much for your in depth explanation and help with the code.
I now have a better understanding of the nature of C++ I think.

I think this will do great for my assignment. Thank you again!
Topic archived. No new replies allowed.