By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,159 Members | 913 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,159 IT Pros & Developers. It's quick & easy.

Converting string to int

P: 1
Hi,



I'm trying to read in a string of the N=348, and convert it into an integer. I have already split the string down to remove the non numeric values and can print the correct value to the screen. When I then try to convert the string of numeric values to an int using the atoi function the code won't compile and comes up with the error below. A small bit of the code is included below the error message, any help would be appreciated. I recognise that there are probably nicer ways of doing this but I am still a novice.



Thanks

Paul



SkinFrition.c++:156: error: cannot convert `std::string' to `const char*' for argument `1' to `int atoi(const char*)'



Expand|Select|Wrap|Line Numbers
  1. void countpoints(int npz[], char *argv[])
  2.  
  3. {
  4.  
  5.   ifstream raw(argv[1]);
  6.  
  7.   string word1, nums;
  8.  
  9.   char wordsplit, charr[10];
  10.  
  11.   bool found = false;
  12.  
  13.   int nnum, nzone = 0;
  14.  
  15.  
  16.  
  17.   while(!raw.fail())
  18.  
  19.   {
  20.  
  21.         getline(raw, word1);
  22.  
  23.         raw >> wordsplit;
  24.  
  25.         string nums;
  26.  
  27.         if (wordsplit == 'N')
  28.  
  29.         {
  30.  
  31.           raw >> wordsplit; // Reads the equals sign
  32.  
  33.           nnum = 0;
  34.  
  35.  
  36.  
  37.           while(wordsplit != ',')
  38.  
  39.           {
  40.  
  41.             raw >> wordsplit;
  42.  
  43.             if (wordsplit != ',')
  44.  
  45.             {
  46.  
  47.               charr[nnum] = wordsplit;
  48.  
  49.               nnum++;
  50.  
  51.             }
  52.  
  53.           }
  54.  
  55.  
  56.  
  57.           for(int i = 0; i < nnum; i++)
  58.  
  59.           {
  60.  
  61.             nums = nums + charr[i];
  62.  
  63.           }
  64.  
  65.         }
  66.  
  67.         npz[nzone] = atoi(nums);
  68.  
  69.         nzone++;
  70.  
  71.       }
  72.  
  73. }
Feb 19 '07 #1
Share this Question
Share on Google+
1 Reply


Ganon11
Expert 2.5K+
P: 3,652
OK, in order to satisfy atoi(), you will need to give the function a character array, rather than a string. You can to this very easily by using the .c_str() function in std::string - Basically, instead of calling

Expand|Select|Wrap|Line Numbers
  1. atoi(myString);
use

Expand|Select|Wrap|Line Numbers
  1. atoi(myString.c_str());
This will take the string and return a character array representing the string - atoi() should be happy with this.
Feb 19 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.