Simple Way To Convert A String To An Integer

(and figure out if the string is an integer in the first place)

Page 1 of 1

4 Replies - 752 Views - Last Post: 24 February 2009 - 05:21 PM Rate Topic: -----

#1 programble  Icon User is offline

  • (cons :dic :head)

Reputation: 49
  • View blog
  • Posts: 1,315
  • Joined: 21-February 09

Simple Way To Convert A String To An Integer

Posted 24 February 2009 - 04:06 PM

How can I...

1. Figure out if a string is a number?
2. Convert that string to an integer?
Is This A Good Question/Topic? 0
  • +

Replies To: Simple Way To Convert A String To An Integer

#2 alf  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 22-February 09

Re: Simple Way To Convert A String To An Integer

Posted 24 February 2009 - 04:09 PM

I'm no expert, but I think atoi might work. http://cplusplus.com...tdlib/atoi.html
Was This Post Helpful? 0
  • +
  • -

#3 crazyjugglerdrummer  Icon User is offline

  • GAME OVER. NERD WINS.
  • member icon

Reputation: 119
  • View blog
  • Posts: 690
  • Joined: 07-January 09

Re: Simple Way To Convert A String To An Integer

Posted 24 February 2009 - 04:15 PM

You can use atoi(string), which takes a C char array and returns an int. That's the simplest (but not always recommended) way for those.

To do C++ strings, you use a string-stream (or convert to C string and use some other method).
Here's an example from Ubuntuforums.
#include <iostream>
#include <sstream>

int main()
{
using namespace std;

string s = "1234";
stringstream ss(s); // Could of course also have done ss("1234") directly.

int i;
ss >> i;
cout << i << endl;

return 0;
}


stringstreams are used for string IO and processing, and have a bunch of useful stuff in them.

Hope this helps!
Was This Post Helpful? 0
  • +
  • -

#4 sparkart  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 113
  • View blog
  • Posts: 688
  • Joined: 16-February 09

Re: Simple Way To Convert A String To An Integer

Posted 24 February 2009 - 04:16 PM

http://www.cplusplus...le/isdigit.html
Was This Post Helpful? 0
  • +
  • -

#5 programble  Icon User is offline

  • (cons :dic :head)

Reputation: 49
  • View blog
  • Posts: 1,315
  • Joined: 21-February 09

Re: Simple Way To Convert A String To An Integer

Posted 24 February 2009 - 05:21 PM

Thanks for your replies, I think I'll use the string stream way.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1