-2

I'm trying to create program in C that reads user input. Correct user input is [number][space][number]. I read every input char and check if there was exactly one space. When comes '\n' I need all input chars were stored in the array. The problem is that I know size of array only when '\n' comes. How can I write input to array? Here is my code:

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

int array_size=0;
char input;
int spaces=0;

int main (){
while ((input = getchar())!=EOF){ 
array_size++;
if(input==' '){ //if user input a space
spaces++;
}

if(spaces>1){
fprintf(stderr, "You can input only one space in row\n");
spaces=0;
array_size=0;
continue;
}
if(input=='\n'){ //if thre is only one space and user inputs ENTER
char content[array_size+1];

//here I know array size and need to add to array all chars that were inputed

content[array_size-1]=='\0'; //content is a string
if((content[0]==' ')||(content[array_size-2]==' ')){
fprintf(stderr, "You can't input space only between numbers\n");
spaces=0;
array_size=0;
continue;
}

//then work with array

spaces=0;
array_size=0;
}

}
exit(0);
}
user2950602
  • 395
  • 1
  • 7
  • 21

2 Answers2

0

Your code is broken. Here is an example. Take it as a starting point.

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

int main(void) {
  char input[10]; // 10 is just an example size
  int c;          // current character read
  int token_no = 0;
  // we read until EOF
  while ((c = getchar()) != EOF) {  //read chars while EOF
    if(c == '\n')  // or newline
      break;
    if (token_no % 2 == 0) {  // if no of token is even, then we expect a number
      if (isdigit(c)) {
        input[token_no++] = c;
      } else {
        printf("Expected number, exiting...\n");
        return -1;
      }
    } else {
      if (c == ' ') {
        input[token_no++] = c;
      } else {
        printf("Expected space, exiting...\n");
        return -1;
      }
    }
  }
  input[token_no++] = '\0'; // here you had ==, which was wrong

  printf("%s\n", input);

  return 0;
}

Output1:

1 2 3
1 2 3

Output2:

123
Expected space, exiting...

Output3:

1       <- I have typed two spaces here
Expected number, exiting...
gsamaras
  • 71,951
  • 46
  • 188
  • 305
0

If you want to dynamically allocate and array, use malloc after determining the size

int *a = (int*)malloc(sizeof(int) * size)

or take a look a these answeres:

can size of array be determined at run time in c?

How to declare the size of an array at runtime in C?

Community
  • 1
  • 1
mchouhan_google
  • 1,775
  • 1
  • 20
  • 28