3

Possible Duplicate:
c++ converting string to int

I have the user input 9 numbers in sequence. I need to convert the string numbers to an int

string num;
int num_int, product[10];

cout << "enter numbers";
cin >> num;

for(int i =0; i<10; i++){
   product[i] = num[i] * 5; //I need the int value of num*5
}
Community
  • 1
  • 1
user1082764
  • 1,973
  • 9
  • 26
  • 40

5 Answers5

5

Why don't you just read immediately to an integer?

int num;
cin >> num;
4

You do not need to have two variables. It's usual in C++ to convert on the fly, in the input stream, without ever seeing the text as a string. So you can simply write:

int num;
std::vector< int > product( 10 );

std::cout << "enter number: ";
std::cin >> num;

...

Note that I've corrected the way you've declared the array as well. You wouldn't normally use int product[10]; in C++. (And you'd almost never define two variables on the same line, even if the language allows it.)

xcdemon05
  • 1,372
  • 5
  • 25
  • 49
James Kanze
  • 150,581
  • 18
  • 184
  • 329
3

The easiest way by far to convert to a string and back again is to use the conversion functions.

 std::string s="56";
 int i=std::stoi(s);

http://en.cppreference.com/w/cpp/string/basic_string/stol

and back

 int i=56;
 std::string s=std::to_string(i);

http://en.cppreference.com/w/cpp/string/basic_string/to_string

of course if you are reading input you might as well do it then and there too

 int i;
 std::cin >> i;
111111
  • 15,686
  • 6
  • 47
  • 62
1

Here is a full sample:

//library you need to include
    #include <sstream>
    int main()
    {
        char* str = "1234";
        std::stringstream s_str( str );
        int i;
        s_str >> i;
    }
tomaytotomato
  • 3,788
  • 16
  • 64
  • 119
1

if you absolutely must use a std::string (for any other reason.. perhaps homework?) then you can use the std::stringstream object to convert it from a std::string to int.

std::stringstream strstream(num);
int iNum;
num >> iNum; //now iNum will have your integer

Alternatively, you can use the atoi function from C to help you with it

std::string st = "12345";
int i = atoi(st.c_str()); // and now, i will have the number 12345

So your program should look like:

vector<string> num;
string holder;
int num_int, product[10];

cout << "enter numbers";
for(int i = 0; i < 10; i++){
    cin >> holder;
    num.push_back(holder);
}
for(int i =0; i<10; i++){
   product[i] = atoi(num[i].c_str()) * 5; //I need the int value of num*5
}
Aniket Inge
  • 25,375
  • 5
  • 50
  • 78