Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How do you split a string:
char *mystring = "12345"
into an integer array which looks like this:
[1, 2, 3, 4, 5]
I have tried something like the code below, but I'm not entirely sure if it's reliable, and I think it will be easy to break. This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(void) {
char *mystring = "12345";
int string_size, i, length;
string_size = strlen(mystring);
int values[string_size];
for (i = 0; mystring[i] != '\0'; i++) {
values[i] = mystring[i] - 48;
}
length = sizeof(values)/sizeof(*values);
for (i = 0; i < length; i++) {
printf("%d ", values[i]);
}
return 0;
}
Which outputs:
1 2 3 4 5
Is there a more C like way I can do this?
The odd thing I see, which isn't itself a problem, is that you calculate the length of the string/array three different ways:
string_size = strlen(mystring);
for (i = 0; mystring[i] != '\0'; i++) {
length = sizeof(values)/sizeof(*values);
where just one method is sufficient:
#include <stdio.h>
#include <string.h>
int main(void) {
char *mystring = "12345";
size_t length = strlen(mystring);
int values[length];
for (int i = 0; i < length; i++) {
values[i] = mystring[i] - '0';
}
for (int i = 0; i < length; i++) {
printf("%d ", values[i]);
}
printf("\n");
return 0;
}
You can replace 48 with '0' for readability.
You can change all loops to loop until string_size like the first one, no need to change the method for each loop.
And finally if you're going to return that array anywhere outside of local function, you should probably malloc() it rather than use a local/stack variable.
But otherwise, it's pretty simple and it works.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have problems with invalid conversion from 'char*' to 'char' [-fpermissive].
In here, I am shifting data one digit.
char text[]="5052.4318" ,temp;
When I write like this, ok, it is working but I need to read data from array[3].
How can I handle this problem?
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
char *array[3];
array[3]="5052.4318";
char text[]={array[3]} ,temp;
int text_len = strlen (text),i;
for (i =0; i <=text_len - 1; i++)
{
if (text[i] == '.')
{
temp = text[i-1];
text[i-1] = text[i];
text[i] = temp;
}
}
printf ("%s\n", text);
return 0;
}
Working
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (void) {
char *array[1] = {"5052.4318"};
size_t text_len = strlen(array[0]);
char text[text_len + 1], temp;
int i;
strcpy(text, array[0]);
for (i=0; i <=text_len - 1; i++){
if (text[i] == '.') {
temp = text[i-1];
text[i-1] = text[i];
text[i] = temp;
}
}
printf ("%s\n", text);
}
In here I am trying read GPS data and this data is GPRMC so firstly i need to parse these data after have to convert to google maps format(latitude need longitude).
$GPRMC,093612.000,A,5052.43525,N,00440.11204,E,0.0,0.0,130917,,,A*6C
5052.43525 is latitude value. Firstly I need to shift data like this 50.5243525.Again shift>>After divide number of 60=> 52.43525/60=0.87392083.
So result should be 50.87392083. Another problem I shouldnt use atof command for string to float value. Because I am using Coocox and is not working in Debug.Maybe I need to use null terminal. I am sharing this code which progressing I am doing.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
//char buf[]
="$GPRMC,121212,A,4807.038,N,01131.000,E,022.4,084.4,030611,003.1,W*6A";
char T[100];
sprintf(T,
"%s","$GPRMC,093612.000,A,5052.43525,N,00440.11204,E,0.0,0.0,130917,,,A*6C");
printf(T);
char *buf[]={T};
int i = 0;
char *p = strtok (*buf, ",");
char *array[12];
while (p !=0)
{
array[i++] = p;
p = strtok (0, ",");
}
for (i = 0; i < 11; ++i) {
array[i];
printf("%s\n",array[i]);
}
//char *array[3] = {"5052.4318"};
size_t text_len = strlen(array[3]);
char text[text_len +1], temp;
int i1;
strcpy(text, array[3]);
for (i1 =0; i1 <=text_len - 1; i1++)
{
if (text[i1] == '.')
{
temp = text[i1-1];
text[i1-1] = text[i1];
text[i1] = temp;
}
}
for (i1 =0; i1 <=text_len - 1; i1++)
{
if (text[i1] == '.')
{
temp = text[i1-1];
text[i1-1] = text[i1];
text[i1] = temp;
}
}
char *buf1[]={text};
int i3 = 0;
char *p1 = strtok (*buf1, ".");
char *array1[2];
while (p1 !=0)
{
array1[i3++] = p1;
p1 = strtok (0, ".");
}
for (i3 = 0; i3 < 2; ++i3) {
array1[i3];
} double d;
float m;
int k=0;
d= (atof(array1[1])/6000);
char s[1]= {d};
m=(atof(array1[0]));
printf("%f\n",m);
printf("%lf\n",d);
return 0;
}
Result should be 50.87392083.
I havent completed.
Thanks
I'm not completely sure what you are trying to achieve but there are some problems with the first part of your code. Your initialization lines are not really correct.
I think that you are trying to "divide by 10" your string. Keeping your algorithm, I've fixed some of the issues to have it compiled.
// #include <iostream> // This is C not C++. Also you include stdio.h...
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
char array[] = "5052.4318"; // This initialization
// one of your errors
char * text = array + 3; // I don't know why you are pointing
// fourth element of the array, but you may do
// in this way
// Let's say I prefer to start from the starting of
// the array
text = array;
printf ("%s\n", text);
int text_len = strlen(text);
for (int i = 1; i <= text_len - 1; i++) { // You will have some problem
// if you start from 0...
if (text[i] == '.') {
char temp; // temp is used only here, so let's define it in the
// only scope that needs it.
temp = text[i - 1]; // This -1 is the reason why you may start
// the for from 1, instead of 0.
text[i - 1] = text[i];
text[i] = temp;
}
}
printf ("%s\n", text);
return 0;
}
It prints out:
5052.4318
505.24318
Is that what you want to achieve?
The for starts from 1 to handle strings like ".1234".
Also: -fpermissive is a flag that controls the "dialect" of the C++ compiler. It is not something that you see when you are compiling in C. Since you included iostream, your compiler switched automatically to a C++ compiler. You must be really careful in this things.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
char text[30]="5052.4318",temp;
int text_len = strlen (text),i;
//printf("%s\n%d\n",text,text_len);
for (i =0; i <=text_len - 1; i++)
{
if (text[i] == '.')
{
temp = text[i-1];
text[i-1] = text[i];
text[i] = temp;
}
}
printf ("%s\n", text);
return 0;
}
You don't need to use an extra character array to achieve your desired result.
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;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Shouldn't st be a array of pointers to char rather than a pointer to char? I do not understand how the latter for loop prints the value?
int main(void)
{
char temp[256];
char *st;
for (int i = 0; i < 3; i++)
{
scanf("%s", temp);
st= strdup(temp);
}
for(int i=0;i<3;i++)
{
printf("%s",st);
}
}
You probably want this:
#include <stdio.h>
#include <string.h>
int main(void)
{
char temp[256];
char *st[3]; // array of three pointers to char
for (int i = 0; i < 3; i++)
{
scanf("%255s", temp); // prevents potential buffer overflow
st[i] = strdup(temp);
}
for(int i = 0; i < 3; i++)
{
printf("%s\n", st[i]);
free(st[i]); // free strduped memory
}
}
This program displays:
./a.out
11
22
33
11
22
33
Whereas your program displays
./a.out
11
22
33
33
33
33
this is because:
char *st; // in your prog. you only declare one pointer
for (int i = 0; i < 3; i++)
{
scanf("%s", temp);
st= strdup(temp); // here you overwrite the st pointer loosing
// the string strduped in the previous run of the loop
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm receiving an uknown error found in the stdio.h library.
Please can someone check it at tell me what is wrong with the code (But I thing it should work fine).
P.S. I'm new here so please don't blame me if this is a bad question.
Code:
#include <stdio.h>
#include <stdlib.h>
// Conversion from a number to a string
char *i2s(int broj);
int main()
{
char string1;
int br, n;
do
{
printf("How much numbers?\n -"), scanf("%d", &n);
} while (n < 1);
for (int i = 0; i < n; i++)
{
printf("\nbr = "), scanf("%d", &br);
string1 = *i2s(br);
printf(" %s", string1);
}
free(string1);
getch();
return 0;
}
char *i2s(int broj)
{
char *pom;
int z=0,br=0,p;
if (broj < 0)
{
z = 1;
broj = -broj;
}
p = broj;
do
{
br++;
p /= 10;
} while (p);
pom = (char *)calloc(br + 1 + z, sizeof(char));
if (z)
pom[0] = '-';
do
{
pom[--br + z] = '0' + broj % 10;
} while (broj /= 10);
return pom;
}
char string1;
free(string1);
string 1 is not a pointer.
Also with the following section you overwrite string1 everytime you run through the loop. that way you have no pointer to free() the memory that you allocate inside your function unless you do it inside the loop.
for (int i = 0; i < n; i++)
{
printf("\nbr = "), scanf("%d", &br);
string1 = *i2s(br);
printf(" %s", string1);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Can anyone give me a complete example of how to generate an Alphanumeric String randomly
like (ARG534UJ6) using C ? I'm completely new to C.
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
This is not working.
As pointed out by #IngoLeonhardt, use % (sizeof(alphanum) - 1) instead of % sizeof(alphanum)
My guess is that you don't have room for your string, try:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
int main(void)
{
char *str = malloc(8 + 1);
/* initialize random seed: */
srand(time(NULL));
gen_random(str, 8);
printf("%s\n", str);
free(str);
return 0;
}