I am working on a program which input large numbers and break them up into elements of 4 to put them into a char array, which will then be converted into an int array using atoi (because for some reason I can't just use atoi with string directly :/). Long story, but I'm avoiding the use of sstream or at(). I can get the string and char array to copy each other by putting them through a loop one by one, but will not work using substr(0,4).
This isn't the actual program but just some exploring that'll explain what I'm trying to say.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string a = "123443216542";
char b[50] = {0};
// Here they will not cooperate.
for (int i = 0; i < a.length()/2; i++)
b[i] = a.substr(0, 2);
// Here they go through fine and copy each other.
for (int i = 0; i < a.length(); i++)
b[i] = a[i];
// This is to see output.
for (int i = 0; i < a.length(); i++)
cout << b[i];
}
What do you guys think? Am I missing something here? Are there any alternatives for going from string to char? And are there any alternatives to sstream and at() for converting from string to int besides atoi?
You can pass a.c_str() to atoi.
Any reason you don't want to use stringstreams?
C library provides some other functions besides atoi:
atol, atof, atof, sscanf