PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 21, 2022

[FIXED] How to convert two characters into a string?

 July 21, 2022     atoi, c, char, integer, string     No comments   

Issue

I've the following string saved into a char array named buffer:

{app_id:9401}

I want to obtain two integers: 94 and 01. I want to convert buffer[8] and buffer[9] into the first integer(94) and buffer[10] and buffer[11] into the second integer (1). I'm trying to do it, but I obtain segmentation fault. Why?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main( void )
{
    char buffer[] = "{app_id:9401}";

    printf("First number:%c%c. Second Number: %c%c\n", buffer[8], buffer[9], buffer[10], buffer[11]);

    char first_number[10] = "";
    strcat(first_number, buffer[8]);
    strcat(first_number, buffer[9]);

    int x = atoi(first_number);
    printf("%d\n", x);
}

Solution

Here is one way, by example. Scan two integers from the string, each with a maximum length of 2.

#include <stdio.h>

int main(void)
{
    char buffer[] = "{app_id:9401}";
    int x, y;
    if(sscanf(buffer + 8, "%2d%2d", &x, &y) == 2)
        printf ("x=%d y=%d\n", x, y);
    return 0;
}

Output:

x=94 y=1

If you don't know where the number is in the string, you can find the colon with

char *cptr = strchr(buffer, ':');


Answered By - Weather Vane
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing