Add user input to array in C -
i'm trying create programme in c reads user input. right user input [number][space][number]
. read every input char , check if there 1 space. when comes '\n'
need input chars stored in array. problem know size of array when '\n'
comes. how can write input array? here 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 space spaces++; } if(spaces>1){ fprintf(stderr, "you can input 1 space in row\n"); spaces=0; array_size=0; continue; } if(input=='\n'){ //if thre 1 space , user inputs come in char content[array_size+1]; //here know array size , need add together array chars inputed content[array_size-1]=='\0'; //content string if((content[0]==' ')||(content[array_size-2]==' ')){ fprintf(stderr, "you can't input space between numbers\n"); spaces=0; array_size=0; continue; } //then work array spaces=0; array_size=0; } } exit(0); }
your code broken. here example. take starting point.
#include <stdlib.h> #include <stdio.h> #include <ctype.h> int main(void) { char input[10]; // 10 illustration size int c; // current character read int token_no = 0; // 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 even, expect number if (isdigit(c)) { input[token_no++] = c; } else { printf("expected number, exiting...\n"); homecoming -1; } } else { if (c == ' ') { input[token_no++] = c; } else { printf("expected space, exiting...\n"); homecoming -1; } } } input[token_no++] = '\0'; // here had ==, wrong printf("%s\n", input); homecoming 0; }
output1:
1 2 3 1 2 3
output2:
123 expected space, exiting...
output3:
1 <- have typed 2 spaces here expected number, exiting...
c arrays input
No comments:
Post a Comment