0

There are two kinds of input that can be provided:

50
b 2 40

I have to distinguish both the cases and then take further actions accordingly. Here's what I have tried:

char input[100];
fgets(input, 100, stdin);
printf("%s", input);
int count = 0;
char a[3][100];
int j=0, i=0;
while(true){

  a[count][j] = input[i];
  j++; i++;

  if(input[i] == '\n'){
    break;
  }
  if(input[i] == ' '){
    count++;
    j = 0;
    i++;
  }
}
printf("%d\n", count);
printf("%s\n", a[0]);
printf("%s\n", a[1]);
printf("%s\n", a[2]);

For example, input:

b 6767 9090

output:

b 6767 9090
b 6767 9090
2
b����
67670
9090

Can somebody help me on how to do this? I was suggested previously to use fgets. As I am a beginner in C, I am having difficulty figuring out how to achieve this.

nishantsingh
  • 4,537
  • 5
  • 25
  • 51
  • possible duplicate: http://stackoverflow.com/questions/1478932/check-if-user-inputs-a-letter-or-number-in-c – Calon Sep 24 '15 at 04:59
  • 2
    You aren't adding a null terminator at `a[count][j]` when you hit a space or carriage return. – Vaughn Cato Sep 24 '15 at 05:01

3 Answers3

1

You should either set a '\0' or null terminator when a space is encountered, or you can previously set all the element of the array with 0 or null like this -

char a[3][100] = {0};

kuro
  • 3,214
  • 3
  • 15
  • 31
1

Also, this program will crash if user inputs string which has more than three words (i.e.., count > 2) since loop while(true) tries until it hits \n character.

0

I found out that the best way to do this would be:

char inp[25];
scanf("%s", inp);
if(inp[0] == 'b'){
  int r, v;
  scanf("%d %d", &r, &v);
}
else{
  int v = atoi(inp);
}
nishantsingh
  • 4,537
  • 5
  • 25
  • 51