0

I want to input an array of integers without giving spaces.

For ex:- 032146548 ,each integer should be stored in array distinctly ,

i.e a[0]=0,a[1]=3,a[2]=2 and so on.

How can i do this ?

3
  • Read it as a string and then convert each character by subtracting '0'. Commented Apr 9, 2014 at 8:17
  • Do you mean arr[i]=getchar()-'0' ? @KlasLindbäck Commented Apr 9, 2014 at 8:19
  • Something like that. You probably want to use isdigit on each character to detect when the sequence of digits ends. Commented Apr 9, 2014 at 8:21

3 Answers 3

1

I think it's clearer to say "each digit", since it's not at all obvious how many "integers" the character sequence 032146548 represents (the common practice is "one") once you know it's supposed to be several.

The simplest way is to just read it in as a string of digits, then convert each digit to its integer counterpart by subtracting '0':

char line[12];
unsigned int a[10];
if(fgets(line, sizeof line, stdin) != NULL)
{
  const size_t digits = strlen(line) - 1;
  for(size_t i = 0; i < sizeof a; ++i)
  {
    if(i < digits && isdigit((unsigned int) line[i]))
       a[i] = line[i] - '0';
    else
       a[i] = 0;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Use this if you are reading from file,

int i=0;
while(scanf("%1d",&a[i])==1)
{
     i++;
}

Use this if you know how many inputs are there,

for(int i=0;i<inputLength;i++)
{
    scanf("%1d",&a[i]);
}

Comments

0
#include <stdio.h>

int main(){
    int a[16];
    int i, j, stat;
    char ch[2] ={0};

    for(i=0;i<16;++i){
        if(1!=(stat=scanf("%1d%1[^0-9]", &a[i], ch))){
            if(stat==2)
                ++i;
            break;
        }
    }
    for(j=0;j<i;++j)
        printf("%d ", a[j]);
    printf("\n");
    return 0;
}

4 Comments

can you explain this: if(1!=scanf("%1d%1[ \t\n]", &a[i], ch)) @BLUEPIXY
@madhurgarg The input character by character number by the loop. The next character in the numbers loop termination in the case of line break.
@BLUEPIXY But OP asked to skip the \n not to stop taking input.
@Tahlil I understand that it's that it does not enter along with the new line one by one and or separated by a space.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.