-5

this is c program to convert number string into integer. I think that the if statement is not getting executed. I want to compare string[a] with the ascii value representented by number in integer i.

    //to convert number string to integer
#include<stdio.h>
#include<string.h>
void main()
{
    int a=0, copy[10]={0},len,i;
    char string[10];
    clrscr();
    puts("enter a number string");
    gets(string);
    len=strlen(string);
    while(a<len)
    {
        for(i=48;i<=57;i++)
        {
            if(string[a]==i)
            {
                copy[a]=i-48;
                break;
            }
            a++;
        }

    }
    for(i=0;i<len;i++)
    printf("%d",copy[i]);
    getch();
}
4
  • Seen this? stackoverflow.com/questions/7021725/… Commented Nov 3, 2017 at 8:32
  • 1
    a++; move to after for-loop. Commented Nov 3, 2017 at 8:33
  • 3
    Hints: 1. don't use TurboC, 2. gets has been deprecated more than a decade ago. 3. Don't use "magic numbers" such as 48 but use '0' instead. Commented Nov 3, 2017 at 8:35
  • Notice the inner loop is comp-letely useless. Commented Nov 3, 2017 at 8:55

1 Answer 1

1

The problem is near break statement, Your break statement is being executed without executing a++;. Here is the correct code.

#include<stdio.h>
#include<string.h>
void main()
{
    int a=0, copy[10]={0},len,i;
    char string[10];
    clrscr();
    puts("enter a number string");
    gets(string);
    len=strlen(string);
    while(a<len)
    {
        for(i=48;i<=57;i++)
        {
            if(string[a]==i)
            {
                copy[a]=i-48;
                a++;
                break;
            }
        }

    }
    for(i=0;i<len;i++)
    printf("%d",copy[i]);
    getch();
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.