IAMBEAST
IAMBEAST

Reputation: 133

dealing with string input in C

I am trying to input string into fixed size char array. I have a questions:

  1. when I input a string which is bigger than the char array, the array become bigger without any additional declaration. I want to make the code only take the string that 'equal or smaller than the char array'.

Thank You.

CODE:

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

/***************************Function****************************/
int string_length(char s[]) {
    int c = 0;

    while (s[c] != '\0')
        c++;

    return c;
}
/**************************************************************/
char *str;
int arrSize;

void opt1()
{
    printf("Enter array size: ");
    scanf("%d", &arrSize);
    arrSize=arrSize+1;
    str = malloc(arrSize);
    return;
}

void opt2()
{
    printf("Enter characters: ");
    scanf("%s", str);

    length = string_length(str);

    printf("your input is '%s'\n", str);
    printf("your input length is '%d'\n", length);

    return;
}

int main()
{
    int input = 0;

    while(input != 3) {
        printf("\n NAME \n");
        printf("\n");

        printf("--------------------------------------\n");
        printf("1) Making Array \n");
        printf("2) Check Array \n");
        printf("3) Quit\n");
        printf("\nEnter selection: ");
        scanf("%d", &input);

        if( input == 1 ) {
            /* */
            opt1();
        }
        else if(input == 2) {
            opt2();
        }


    }
    return 1;
}

Upvotes: 0

Views: 85

Answers (2)

lost_in_the_source
lost_in_the_source

Reputation: 11237

To read in a whole line, you can use fgets:

char line[80];

if (fgets(line, sizeof line, stdin) != NULL) {
    // use the input
}

Now you won't need to check if the user entered more than the limit, since fgets will only get the first 79 (-1 for null terminator) characters; the remainder, if any, will be ignored.

Upvotes: 1

chux
chux

Reputation: 153468

OP wants to read data, yet if larger that the target array, then do not change the target array.

// 1: success
// -1 EOF
// 0: Input too long
int read_array(char *buffer, size_t size) {
  char tmp[size];
  size_t i = 0;
  int ch;

  while ((ch = fgetc(stdin)) != EOF && ch != '\n') {
    if (i < size) { 
      tmp[i++] = ch;
    }
  }

  if (ch == EOF && i == 0) return EOF;
  if (i >= size) return 0;  // too many
  memcpy(buffer, tmp, i);
  buffer[i] = '\0';
  return 1;
}     

Normally code could use fgets(), but there are corner cases that fail to meet OP goals.

Upvotes: 2

Related Questions