Link to home
Start Free TrialLog in
Avatar of xneo27
xneo27

asked on

c++ substring to char

Okay I want to take a single char from a sting and place into a char variable.
Heres my current code:

//The convert function takes a string of numbers and returns its integer value.
int convert(string strNum)
{
      char c;
      const int Size = strNum.size();
      int I;
      int J;
      int X;
      int Y;
      int total;
      int tmpint1;
      int tmpint2;
      const int plusone = Size + 1;
      
      for(I = 1; I < plusone; I++)
      {
            X = Size - I;
            if (X > 0)
            {
                  Y = 10;
                  for(J = 1; J < X; J++)
                  {
                        Y = Y * 10;
                  }
            }
            else Y = 1;
            c = strNum.substr(I,I);
            tmpint1 = c - '0';
            tmpint2 = tmpint1 * Y;
            total = total + tmpint2;
      }
      return total;
}

The only error with it is:

sr1 $ CC -o Program08 Program08.cpp
"Program08.cpp", line 182: Error: Cannot assign std::string  to char.
1 Error(s) detected.

How could I fix this?
Avatar of rmahesh
rmahesh

This should work:

c = strNum.at(I);

Mahesh

But I believe that you want to do this conversion yourself for some reason.

Hope you know "atoi" and related functions doing the same.
Avatar of xneo27

ASKER

is there any other way to do it, see I dont think that I am allowed to use either of those methods
Why not just use builtin c++ functions to do your convertion

e.g.

#include <stdlib.h>

atoi(strNum.c_str());
You should just be able to call atoi ... ( atoi(strNum.c_str()); )  whats the error you get when u try to call?
if it is a c++ string, you can simply do c = strNum[i] where string::size_type i = 0; i < strNum.length(); ++i
strNum.at(i) is its functional equivalent
ASKER CERTIFIED SOLUTION
Avatar of Ehsan_Noureddin
Ehsan_Noureddin

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial