Was not sure what you are specifically looking for, below is a function you can pass input of form
1 2
3 4
5 6
...
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int * str_to_int(char *lines) {
int *int_arr;
int i, offset, index;
// alloc mem for int arr
int_arr = malloc(sizeof(int) * (strlen(lines) / 2));
index = 0;
// using sscanf() "convert" string to int
while(sscanf(lines, "%d%n", &i, &offset) == 1) {
// offset increments ptr to lines
lines += offset;
int_arr[index++] = i;
}
return int_arr;
}
Answer from Cathal OGrady on Stack OverflowHow do I convert a string in C++ or C to an integer array? - Stack Overflow
Converting string to integer array in c - Stack Overflow
atoi - Best Way to Convert Array of Strings to Array of Int in C - Stack Overflow
c - Converting 'integer strings' to integer array - Stack Overflow
You might be overthinking things. Here's a simply way to input numbers from a user that doesn't involve formatting or parsing strings.
int numArray[31];
int i = 0;
int num = 0;
while( scanf("%d", &num) > 0 && i < 31 && num >0) {
numArray[i] = num;
i++;
}
The loop will stop when the user enters a negative number, or has entered all 31 possible numbers.
You still have to make sure the user enters a number between 0 and 31 though!
You can use a library or you can write a helper function. The helper function would look something like this (pseudocode):
int output = 0;
for (int i = 0; i < string.length; i++) {
output = output * 10;
output = output + parse(string[i]) //parse first character into a single digit
}
For example, if you have 253, it will read 2. Then it will multiply it by 10 (20) and add 5 (25). Then it will multiply that by 10 (250) and add 3, which will be the expected output.
Note that you need to find a way to parse a single character of your string into a single digit integer - that should be very easy using something like a switch() statement.
EDIT: If you are looking for a library function, check out this question:
What is the difference between sscanf or atoi to convert a string to an integer?
As you said in the comments, you got a binary string and you want to convert it into integers. Use bitset for that:
std::istringstream is(str);
std::bitset<32> bits; // assuming each num is 32 bits long
while(is >> bits) {
unsigned long number = bits.to_ulong();
// now, do whatever you want with that long.
v.push_back(number);
}
If you only have one binary number in that string str, you can get away with
unsigned long number = std::bitset<32>(str).to_ulong();
Converting that in C is also possible...
long value;
char const *c = str;
for(;;) {
char * endp;
value = strtol(c, &endp, 2);
if(endp == c)
break;
/* huh, no vector in C. You gotta print it out maybe */
printf("%d\n", value);
c = endp;
}
atoi can't parse binary numbers. But strtol can parse them if you tell it the right base.
How exactly would you like the conversion to work? Do you simply want an array containing the ASCII value of each character in the array? (so "abc" becomes [97, 98, 99, 0])?
Or do you want to parse the string somehow? ("1, 2, 3" becomes an array [1, 2, 3])
In the first case, in C++, I'd do something like this:
struct convert {
int operator()(char c) {
return static_cast<int>(c);
}
};
std::string str = "hello world";
std::vector<int> result;
std::transform(str.begin(), str.end(), std::back_inserter(result), convert())
Of course you could use a raw array instead of the vector, but since the length of the string is probably going to be variable, and then arrays are just asking for trouble.
If this wasn't what you wanted, you might want to edit your question to be more specific.
Use these functions:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef int16_t gint16; // define gint16 if not compiling with glib.h
char *gint16_to_string(gint16 *p, int n) {
char *str = malloc(n * 4 + 1);
if (str) {
for (int i = 0; i < n; i++) {
snprintf(str + i * 4, 5, "%04X", p[i] & 0xFFFF);
}
}
return str;
}
void string_to_gint16(gint16 *p, int n, const char *str) {
if (str) {
for (int i = 0; i < n; i++) {
unsigned int x = 0;
sscanf(str + i * 4, "%4x", &x);
p[i] = (gint16)x;
}
}
}
int main(void) {
gint16 frame[5] = { 10, 2, 3, 7, 5 };
// encoding in hexadecimal
char *str = gint16_to_string(frame, 5);
printf("encoded string: %s\n", str);
// from hexa string to 16 bit integer array
gint16 n_oframe[5];
string_to_gint16(n_oframe, 5, str);
printf("n_oframe: ");
for (int i = 0; i < 5; i++) {
printf("%d, ", n_oframe[i]);
}
printf("\n");
free(str);
return 0;
}
The commenters found most of it, so to put it all together
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
// ALL CHECKS OMMITTED!
int main()
{
int16_t frame[5] = { 10, 2, 3, 7, 5 };
// hexadecimal string = 2 characters plus NUL
// sizeof(char) == 1, if compiler is standard compliant
char *str = malloc(3 * (sizeof(frame)/sizeof(frame[0]) +1));
char *strp = str;
size_t j;
for (j = 0; j < sizeof(frame)/sizeof(frame[0]); j++) {
// again: hexadecimal string = 2 characters plus NUL
snprintf(strp, 3, "%02x", frame[j]); //hexadecimal
strp += 2;
}
// we need a pointer to the start of the string to free it later
strp = str;
// let's see if we gott all of them
printf("str = %s\n",str);
// from hexa string to 16 bit integer array
int16_t n_oframe[5];
size_t i_m;
// and again: hexadecimal string = 2 characters plus NUL
// a simple char d[3]; would have been more than suffcient
// for the task, but if stack is precious...
char *d = (char *) malloc(3);
for (i_m = 0; i_m < 5; i_m++) {
// it's always the same, just do it once at the beginning
//char *d = (char *) malloc(3);
strncpy(d, str, 2);
// atol() is for base 10 input only, use strtol() instead
n_oframe[i_m] = (int16_t)strtol(d,NULL,16);
str = str + 2;
//free(d);
}
for (j = 0; j < 5; j++) {
printf("%d ", n_oframe[j]);
}
putchar('\n');
free(d);
free(strp);
exit(EXIT_SUCCESS);
}
I changed gint16 to int16_t because I do not know what that is supposed to be. You can most likely replace it with gint16 without problems.
Assuming argc and argv are the arguments passed to main, it is unlikely that argv[0] is something that you want to convert into an integer. argv[0] usually contains the name of the program.
Your code snippet is declaring an array local to the loop body. What you likely want is an array defined outside the loop body, and you want to assign to individual array elements within the loop body.
int arr[argc];
for(i = 1; i < argc; i++)
{
arr[i] = atoi(argv[i]);
}
You are declaring your array arr every time you loop.
change your loop like this:
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int arr[argc];
int i=0;
for(i = 0; i < argc-1; i++)
{
arr[i] = atoi(argv[i+1]);
printf("arr[%d] = %d\n",i,arr[i]);
}
return 0;
}
Here is the output:
Sukhvir@Sukhvir-PC ~
$ gcc -Werror -Wall -g -o test test.c
Sukhvir@Sukhvir-PC ~
$ ./test 3 4 5
arr[0] = 3
arr[1] = 4
arr[2] = 5
You can access each element in your string using the [] operator, which will return a reference to a char. You can then deduct the int value for char '0' and you will get the correct int representation.
for(int i=0;i<userstr.length();i++){
myarray[i] = userstr[i] - '0';
}
int* myarray = new int[ userstr.size() ];
std::copy( usestr.begin(), userstr.end(), myarray );
The terminating zero was not appended to the array. If you need it you should allocate the array having one more element and place the terminating zero yourself.