4

I'm trying to input a series of numbers (i.e. 123456789), and then having output it each one at a time (i.e. 1, 2, 3, ... , 9). However, after the 9, which is str[9] onwards, the output value would be random numbers such as -48, 32, 9, -112. How do I make sure the output numbers stops at 9, since the last number I had input was 9?

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

int main()
{
  char str[100];
  int n,num[100];
  scanf("%s", str);
  for(n=0;n<100;n++)
    {
      num[n] = str[n] - '0';
      printf("%d\n", num[n]);
    }
  return 0;
}
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
M.H.F
  • 81
  • 2
  • 5

4 Answers4

0

The string you input from scanf might be less than 100 chars, use strlen to get its size:

int main(void)
{
    char str[100] = {0};
    int num[100];
    size_t len, n;
    scanf("%s", str);
    len = strlen(str);
    for(n=0;n<len;n++)
    {
        num[n] = str[n] - '0';
        printf("%d\n", num[n]);
    }
    return 0;
}

Note you should use int main(void), not int main().

fluter
  • 13,238
  • 8
  • 62
  • 100
0
  • You need to take length of you input string, Use strlen(str) , And store that value in one variable and up to string length rotate the loop. That's it:

  • Here, I did :

#include<stdio.h>
#include<string.h>
int main()
{
 char str[100] = {};
 int n = 0,count = 0,num[100] = {};
 scanf(" %s", str);
 count = strlen(str);
 for(n = 0; n < count; n++) 
 {
   num[n] = str[n] - '0';
   printf("%d\n", num[n]);  
 } 
 return 0;
}
0

you can compare ascii value.

#include<string.h>
#include<stdio.h>
int main(){
 char str[100];
 int n,num[100]=0;
 scanf("%s", str);
 while(str[n]<58 && str[n]>47){
  num[n] = n*num[n]+str[n];
 n++; 
}
printf("%d\n", num[n]);
return 0;

}

0

Seems like you should be processing the input once character at a time instead of as a string. This would eliminate the need for the seemingly arbitrary 100 char limit. You could validate that the character is a digit before printing, terminating the loop when the first non-digit it found.

#include <ctype.h>
char c;
scanf( "%c", c );
while (isdigit(c))
{
    printf("%c\n", c );
}