This question already has answers here:
Split string into tokens and save them in an array
(3 answers)
Closed 3 years ago.
I'm working on a project for my class and have come upon a roadblock. Let's say I have a space separated character array (string) that contains numbers (each followed by a space character). Assume it looks something like this:
0 1 15 10 6 2
The number of items in it will never be constant so I cannot use sscaf() to get all the numbers. I tried looping trough it as characters but I ended up separating the double digit numbers messing things up.
Can someone guide me on how I can get each number in the string and save it to a int array without separating the double digit ones? I'm writing this in C
Thanks in advance
Another solution to your problem would be to navigate through the string and add the characters into a buffer until you hit an empty space, then have a function that takes that buffer and converts it into a number.
But before that we have to count the number of empty spaces, since that will tell us the number of integers we have, or you could have a default value for the array of integers and realloc when there are more numbers than the default value.
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define WHITE_SPACE (0x20)
int32_t
get_len_numbers(const char *str) {
int32_t n;
const char *ptr;
ptr = str;
n = 0;
for(; *ptr != 0; ++ptr)
n += (*ptr == ' ');
return(n + 1);
}
int32_t
stoi(const char *number) {
int32_t n;
n = 0;
for(; *number != 0; ++number)
n = (n * 10) + (*number & 0x0F);
return(n);
}
int main(void) {
int32_t len;
register int32_t i;
register int32_t j;
uint8_t buf[32];
char *str;
int32_t *numbers;
str = "1 5 25 30 99";
len = get_len_numbers(str);
numbers = malloc(sizeof(int) * len);
if(numbers == NULL)
exit(EXIT_FAILURE);
for(i = 0, j = 0; ; ++str) {
if(*str == WHITE_SPACE || *str == 0) {
buf[i] = 0;
numbers[j++] = stoi(&buf[0]);
i = 0;
if(*str == 0)
break;
} else {
buf[i++] = *str;
}
}
return(0);
}
how I can get each number in the string and save it to a int array without separating the double digit ones?
Scan the string once to find the number of int
Define the array
Scan again and save into the array
...
const char *s = "0 1 15 10 6 2 ";
int count = scans_ints(s, NULL);
if (count <= 0) Handle_Bad_intput();
else {
int arr[count];
sscan_ints(s, arr);
}
Possible sscan_ints() (untested)
#include <ctype.h>
#include <limits.h>
int sscan_ints(const char *s, int *arr) {
int count = 0;
for (;;) {
// Consume leading spaces: ease detection of end-of-line
while (isspace((unsigned char) *s)) s++;
if (*s == '\0') break;
char *endptr; // Location where conversion ended
errno = 0;
long num = strtol(s, &endptr, 10);
if (s == endptr) return -1; // non-numeric text
if (errno || num < INT_MIN || num > INT_MAX) return -1; // number too big
if (arr) {
arr[count] = (int) num;
}
count++;
s = endptr;
}
return count;
}
Related
I'm trying to convert an integer to a binary String (see code below). I've already looked at several similar code snippets, and can't seem to find the reason as to why this does not work. It not only doesn't produce the correct output, but no output at all. Can somebody please explain to me in detail what I'm doing wrong?
#include <stdio.h>
#include <stdlib.h>
char* toBinaryString(int n) {
char *string = malloc(sizeof(int) * 8 + 1);
if (!string) {
return NULL;
}
for (int i = 31; i >= 0; i--) {
string[i] = n & 1;
n >> 1;
}
return string;
}
int main() {
char* string = toBinaryString(4);
printf("%s", string);
free(string);
return 0;
}
The line
string[i] = n & 1;
is assigning integers 0 or 1 to string[i]. They are typically different from the characters '0' and '1'. You should add '0' to convert the integers to characters.
Also, as #EugeneSh. pointed out, the line
n >> 1;
has no effect. It should be
n >>= 1;
to update the n's value.
Also, as #JohnnyMopp pointed out, you should terminate the string by adding a null-character.
One more point it that you should check if malloc() succeeded. (It is done in the function toBinaryString, but there is no check in main() before printing its result)
Finally, It doesn't looks so good to use a magic number 31 for the initialization of for loop while using sizeof(int) for the size for malloc().
Fixed code:
#include <stdio.h>
#include <stdlib.h>
char* toBinaryString(int n) {
int num_bits = sizeof(int) * 8;
char *string = malloc(num_bits + 1);
if (!string) {
return NULL;
}
for (int i = num_bits - 1; i >= 0; i--) {
string[i] = (n & 1) + '0';
n >>= 1;
}
string[num_bits] = '\0';
return string;
}
int main() {
char* string = toBinaryString(4);
if (string) {
printf("%s", string);
free(string);
} else {
fputs("toBinaryString() failed\n", stderr);
}
return 0;
}
The values you are putting into the string are either a binary zero or a binary one, when what you want is the digit 0 or the digit one. Try string[i] = (n & 1) + '0';. Binary 0 and 1 are non-printing characters, so that's why you get no output.
#define INT_WIDTH 32
#define TEST 1
char *IntToBin(unsigned x, char *buffer) {
char *ptr = buffer + INT_WIDTH;
do {
*(--ptr) = '0' + (x & 1);
x >>= 1;
} while(x);
return ptr;
}
#if TEST
#include <stdio.h>
int main() {
int n;
char str[INT_WIDTH+1]; str[INT_WIDTH]='\0';
while(scanf("%d", &n) == 1)
puts(IntToBin(n, str));
return 0;
}
#endif
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char * compress(char *input, int size){
char *inputa;
char compressedString[100];
inputa = (char*)malloc(sizeof(size));
snprintf (inputa, size, "%s", input);
int i = 0;
int x;
int counter;
while(i < size){
counter = 1;
x = i;
while (inputa[x] == inputa[x + 1] && (x+1) < size){
x++;
counter++;
}
if (i != x){
i = x;
}else{
i++;
}
}
return inputa;
}
main(){
char ez[] = "blaablaaa";
printf("%s \n", compress(ez, sizeof(ez)));
printf("%s", ez);
return 0;
}
So, I am trying to make this function that compresses consecutive characters (eg. "blaablaaa" to "bla2bla3"). My thought process is to put the inputa[x] on the compressed array and next to it the counter, but I can't seem to make it to work.
Lets take a look at these two lines:
inputa = (char*)malloc(sizeof(size));
snprintf (inputa, size, "%s", input);
size has type int, so sizeof(size) is the size of an integer, which is probably 4.
You used malloc to allocate 4 bytes.
Then you use snprintf to try to copy all of your input (blaablaaa, 10-bytes long) into a buffer that is only 4 bytes long.
10 bytes won't fit into a 4 byte buffer.
I'm not sure what you're trying to do there, but it is not correct.
1) Your allocated buffer was too short:
inputa = (char*)malloc(sizeof(size));
It allocates only 4 bytes.
You needed
inputa = (char*)malloc(sizeof(char)*size + 1 ));
2) You forgot to release the allocated memory.
3) The algorithm itself needed the improvements. Comments in the code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
/* reverse: reverse string s in place */
void reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
/* itoa is not a standard function */
/* itoa: convert n to characters in s */
void itoa1(int n, char s[])
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
char * compress(char *input, int size){
int i = 0;
int r; // number of repetitions
char add[2]; // current character buffer
char rep[32]; // repetitions buffer
char c; // current character
char *compr = (char* )malloc(sizeof(char)*size + 1); // memory for the compressed string
compr[0] = 0; // terminate the buffer
add[1] = 0; // terminate the buffer
while(i < size){
c = add[0] = input[i]; // get a character
strcat(compr,add); // add to compr
r = 1; // default number of repetitions is one
while(1) // count and add to the string
{
if(c == input[i+1] )
{ // find how many characters follows c
r++; // number of repetition
i++; // moving along the input buffer
}
else
{
// check the r for number of repetitions
if( r > 1)
{
// there were repetitions:
// char * itoa ( int value, char * str, int base );
itoa1(r,rep); // get the number
strcat(compr,rep); // add repetition number to the compressed string
}
i++;// advance to the next character
break;
} // else
}// while
} //while
return compr;
}
int main(void){
char sg7[] = "BLaaaBBLLaaaaXXXaaY";
char ez[] = "blaablaaa";
char *ptr;
printf("%s \n", ptr = compress(sg7, strlen(sg7) ) );
printf("%s \n", sg7);
free(ptr);
printf("\n");
printf("%s \n", ptr = compress(ez, strlen(ez)));
printf("%s \n", ez);
free(ptr);
return 0;
}
Output:
BLa3B2L2a4X3a2Y
BLaaaBBLLaaaaXXXaaY
bla2bla3
blaablaaa
I hope it helps.
I am self teaching C programming.
I am trying to count number of int present in given string which are separated by space.
exp:
input str = "1 2 11 84384 0 212"
output should be: 1, 2, 11, 84384, 0, 212
total int = 6
When I try. It gives me all the digits as output which make sense since I am not using a right approach here.
I know in python I can use str.split (" ") function which can do my job very quickly.
But I want to try something similar in C. Trying to create my own split method.
#include <stdio.h>
#include <string.h>
void count_get_ints(const char *data) {
int buf[10000];
int cnt = 0, j=0;
for (int i=0; i<strlen(data); i++) {
if (isspace(data[i] == false)
buf[j] = data[i]-'0';
j++;
}
printf("%d", j);
}
// when I check the buffer it includes all the digits of the numbers.
// i.e for my example.
// buf = {1,2,1,1,8,4,3,8,4,0,2,1,2}
// I want buf to be following
// buf = {1,2,11,84384,0,212}
I know this is not a right approach to solve this problem. One way to keep track of prev and dynamically create a memory using number of non space digits encountered.
But I am not sure if that approach helps.
You want to build your number incrementally until you hit a space, then put that into the array. You can do this by multiplying by 10 then adding the next digit each time.
void count_get_ints(const char *data) {
int buf[10000];
int j = 0;
int current_number = 0;
// Move this outside the loop to eliminate recalculating the length each time
int total_length = strlen(data);
for (int i=0; i <= total_length; i++) {
// Go up to 1 character past the length so you
// capture the last number as well
if (i == total_length || isspace(data[i])) {
// Save the number, and reset it
buf[j++] = current_number;
current_number = 0;
}
else {
current_number *= 10;
current_number += data[i] - '0';
}
}
}
I think strtok will provide a cleaner solution, unless you really want to iterate over every char in the string. It has been a while since I did C, so please excuse any errors in the code below, hopefully it will give you the right idea.
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[19] = "1 2 11 84384 0 212";
const char s[2] = " ";
char *token;
int total;
total = 0;
token = strtok(str, s);
while (token != NULL) {
printf("%s\n", token);
total += atoi(token);
token = strtok(NULL, s);
}
printf("%d\n", total);
return 0;
}
You can check the ascii value of each character by doing c-'0'. If it's between [0,9], then it's an integer. By having a state variable, when you're inside an integer by checking if a given character is a number of space, you can keep track of the count by ignoring white space. Plus you don't need a buffer, what happens if data is larger than 10,000, and you write pass the end of the buffer?, undefined behavior will happen. This solution doesn't require a buffer.
Edit, the solution now prints the integers that are in the string
void count_get_ints(const char *data) {
int count = 0;
int state = 0;
int start = 0;
int end = 0;
for(int i = 0; i<strlen(data); i++){
int ascii = data[i]-'0';
if(ascii >= 0 && ascii <= 9){
if(state == 0){
start = i;
}
state = 1;
}else{
//Detected a whitespace
if(state == 1){
count++;
state = 0;
end = i;
//Print the integer from the start to end spot in data
for(int j = start; j<end; j++){
printf("%c",data[j]);
}
printf(" ");
}
}
}
//Check end
if(state == 1){
count++;
for(int j = start; j<strlen(data); j++){
printf("%c",data[j]);
}
printf(" ");
}
printf("Number of integers %d\n",count);
}
I believe the standard way of doing this would be using sscanf using the %n format specifier to keep track of how much of the string is read.
You can start with a large array to read into -
int array[100];
Then you can keep reading integers from the string till you can't read anymore or you are done reading 100.
int total = 0;
int cont = 0;
int ret = 1;
while(ret == 1 && total < 100) {
ret = sscanf(input, "%d%n", &array[total++], &cont);
input += cont;
}
total--;
printf("Total read = %d\n", total);
and array contains all the numbers read.
Here is the DEMO
Example using strtol
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <errno.h>
#include <ctype.h>
int count_get_ints(int output[], int output_size, const char *input) {
const char *p = input;
int cnt;
for(cnt = 0; cnt < output_size && *p; ++cnt){
char *endp;
long n;
errno = 0;
n = strtol(p, &endp, 10);
if(errno == 0 && (isspace((unsigned char)*endp) || !*endp) && INT_MIN <= n && n <= INT_MAX){
output[cnt] = n;
while(isspace((unsigned char)*endp))
++endp;//skip spaces
p = endp;//next parse point
} else {
fprintf(stderr, "invalid input '%s' in %s\n", p, __func__);
break;
}
}
return cnt;
}
int main(void) {
const char *input = "1 2 11 84384 0 212";
int data[10000];
int n = sizeof(data)/sizeof(*data);//number of elements of data
n = count_get_ints(data, n, input);
for(int i = 0; i < n; ++i){
if(i)
printf(", ");
printf("%d", data[i]);
}
puts("");
}
Assuming you don't have any non-numbers in your string, you can just count the number of spaces + 1 to find the number of integers in the string like so in this pseudo code:
for(i = 0; i < length of string; i++) {
if (string x[i] == " ") {
Add y to the list of strings
string y = "";
counter++;
}
string y += string x[i]
}
numberOfIntegers = counter + 1;
Also, this reads the data between the white spaces. Keep in mind this is pseudo code, so the syntax is different.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I got string containing numbers separated by spaces. Numbers can be single-digit, two-digit, or perhaps more-digit. Check the example.
"* SEARCH 2 4 5 12 34 123 207"
I don't know how long the string is (how many numbers it contains), so I cant initiate the array properly. The result should look like this:
array = {2,4,5,12,34,123,207}
Do you have any ideas how to perform this?
like this:
#include <stdio.h>
#include <stdlib.h>
int main(void){
char *input = "* SEARCH 2 4 5 12 34 123 207";
int len = 0;
sscanf(input, "%*[^0-9]%n", &len);//count not-digits(The Number isn't negative)
char *p = input + len;
char *start = p;
int v, n = 0;
while(1 == sscanf(p, "%d%n", &v, &len)){
++n;//count elements
p += len;
}
int array[n];//or allocate by malloc(and free)
char *endp = NULL;
int i;
for(i = 0; i < n; ++i){
array[i] = strtol(start, &endp, 10);
start = endp + 1;
}
//check print
for(i = 0; i < n; ++i)
printf("%d ", array[i]);
puts("");
return 0;
}
You can try this approach. It uses a temporary buffer to hold the current integer that is being processed. It also uses dynamic arrays, to deal with different lengths of the string you want to process, and expands them when necessary. Although using strtok Would be better in this situation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int
main(int argc, char *argv[]) {
char message[] = "* SEARCH 2 4 5 12 34 123 207";
char *buffer = NULL;
int *integers = NULL;
int buff_size = 1, buff_len = 0;
int int_size = 1, int_len = 0;
int ch, messlen, i, first_int = 0;
/* creating space for dynamic arrays */
buffer = malloc((buff_size+1) * sizeof(*buffer));
integers = malloc(int_size * sizeof(*integers));
/* Checking if mallocs were successful */
if (buffer == NULL || integers == NULL) {
fprintf(stderr, "Malloc problem, please check\n");
exit(EXIT_FAILURE);
}
messlen = strlen(message);
/* going over each character in string */
for (ch = 0; ch < messlen; ch++) {
/* checking for first digit that is read */
if (isdigit(message[ch])) {
first_int = 1;
/* found, but is there space available? */
if (buff_size == buff_len) {
buff_size++;
buffer = realloc(buffer, (2*buff_size) * sizeof(*buffer));
}
buffer[buff_len++] = message[ch];
buffer[buff_len] = '\0';
}
/* checking for first space after first integer read */
if (isspace(message[ch]) && first_int == 1) {
if (int_size == int_len) {
int_size++;
integers = realloc(integers, (2*int_size) * sizeof(*integers));
}
integers[int_len] = atoi(buffer);
int_len++;
/* reset for next integer */
buff_size = 1;
buff_len = 0;
first_int = 0;
}
/* for last integer found */
if (isdigit(message[ch]) && ch == messlen-1) {
integers[int_len] = atoi(buffer);
int_len++;
}
}
printf("Your string: %s\n", message);
printf("\nYour integer array:\n");
for (i = 0; i < int_len; i++) {
printf("%d ", integers[i]);
}
/* Being careful and always free at the end */
/* Always a good idea */
free(integers);
free(buffer);
return 0;
}
You can read each character and verify if it is in range of >=48(Ascii of 0) and less than = 57(Ascii of 9). If so is the case read them into a array Otherwise you could copy them to a temporary string and convert to int using functions like atoi()
#include <stdio.h>
int main(int argc, char *argv[])
{
int j=0,k,res;
char buff[10];
while(str[j])
{
if((str[j]>='0')&&(str[j]<='9'))
{
k=0;
while((str[j]!=' ')&&(str[j]!='\0'))
{
buff[k]=str[j++];
k++;
}
buff[k]=0;
res=atoi(buff);
//Store this result to an array
}
j++;
}
return 0;
}
Suppose n numbers are to be input in a single line without any spaces given the condition that these numbers are subject to the condition that they lie between 1 and 10.
Say n is 6 , then let the input be like "239435"
then if I have an array in which I am storing these numbers then I should get
array[0]=2
array[1]=3
array[2]=9
array[3]=4
array[4]=3
I can get the above result by using array[0]=(input/10^n) and then the next digit
but is there a simpler way to do it?
Just subtract the ASCII code of 0 for each digit and you get the value of it.
char *s = "239435"
int l = strlen(s);
int *array = malloc(sizeof(int)*l);
int i;
for(i = 0; i < l; i++)
array[i] = s[i]-'0';
update
Assuming that 0 is not a valid input and only numbers between 1-10 are allowed:
char *s = "239435"
int l = strlen(s);
int *array = malloc(sizeof(int)*l);
int i = 0;
while(*s != 0)
{
if(!isdigit(*s))
{
// error, the user entered something else
}
int v = array[i] = *s -'0';
// If the digit is '0' it should have been '10' and the previous number
// has to be adjusted, as it would be '1'. The '0' characater is skipped.
if(v == 0)
{
if(i == 0)
{
// Error, first digit was '0'
}
// Check if an input was something like '23407'
if(array[i-1] != 1)
{
// Error, invalid number
}
array[i-1] = 10;
}
else
array[i] = v;
s++;
}
E.g.
int a[6];
printf(">");
scanf("%1d%1d%1d%1d%1d%1d", a,a+1,a+2,a+3,a+4,a+5);
printf("%d,%d,%d,%d,%d,%d\n", a[0],a[1],a[2],a[3],a[4],a[5]);
result:
>239435
2,3,9,4,3,5
You can use a string to take the input and then check each position and extact them and store in an array. You need to check for the numeric value in each location explicitly, as you are accepting the input as a string. For integers taken input as string, there's no gurantee that the input is pure numeric and if it is not, things can go wild.
check this code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char ipstring[64];
int arr[64];
int count, len = 0;
printf("Enter the numbersi[not more than 64 numbers]\n");
scanf("%s", ipstring);
len = strlen(ipstring);
for (count = 0; count < len ; count++)
{
if (('0'<= ipstring[count]) && (ipstring[count] <= '9'))
{
arr[count] = ipstring[count] - '0';
}
else
{
printf("Invalid input detectde in position %d of %s\n", count+1, ipstring );
exit(-1);
}
}
//display
for (count = 0; count < len ; count++)
{
printf("arr[%d] = %d\n", count, arr[count]);
}
return 0;
}