Converting string to integer.

Dec 13, 2016 at 12:52am
Hello so i posted another forum earlier but I decided to change it and ended up making this. How can i convert the string into int? line 38.

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 <fstream>
#include <conio.h>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    char user_info= ' ';
    string string_convert;
    int num1;
    bool bfail=true;


    do
    {
        bfail=true;
        cout << "Enter num1: ";
        while(user_info != '\n')
        {
            cin.get(user_info);
            if(isdigit(user_info))
                string_convert+=user_info;
            else if(user_info=='\n')
            {
                user_info=='\n';
                if(bfail==false)
                    string_convert="";
            }
            else
                bfail=false;
        }
        user_info=' ';
    }while(bfail!=true);

    //num1 = string_convert;   this tries to conver the string into int

    cout << endl << num1;

    return 0;
}
Last edited on Dec 13, 2016 at 12:52am
Dec 13, 2016 at 12:56am
numl = atoi(string_convert.c_str());
Dec 13, 2016 at 12:58am
I just tried to input that and I entered
 
123

It ended up giving me
 
-2
Dec 13, 2016 at 1:03am
maybe the value of "string_convert" isnt expected, please
cerr << string_convert; to see the value.
Dec 13, 2016 at 1:07am
So i tried what you said and well for some reason even with the following change is cout -2.

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

#include <iostream>
#include <fstream>
#include <conio.h>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;

int main()
{
    char user_info= ' ';
    string string_convert;
    int num1;
    bool bfail=true;


    do
    {
        bfail=true;
        cout << "Enter num1: ";
        while(user_info != '\n')
        {
            cin.get(user_info);
            if(isdigit(user_info))
                string_convert+=user_info;
            else if(user_info=='\n')
            {
                user_info=='\n';
                if(bfail==false)
                    string_convert="";
            }
            else
                bfail=false;
        }
        user_info=' ';
    }while(bfail!=true);
   // cerr << string_convert;

    return 0;
}
Last edited on Dec 13, 2016 at 1:08am
Dec 13, 2016 at 1:29am
I tried your program and it's OK, you can see the result in http://ideone.com/9DWl0E
Dec 13, 2016 at 1:35am
Thank you for the assistance LukeShen. Me and the group I'm in have been stumped on this all day.
Last edited on Dec 13, 2016 at 1:36am
Topic archived. No new replies allowed.