Search code examples
arrayscstringwhile-loopscanf

How to store string value in specific index of array using while loop


I wanted to store string values at a particular index of the character array using a while loop.

Condition for while loop termination: 'q' should be pressed to stop taking input

My Code so far

  char s[100],in;
  int count = 0;
  printf("Enter individual names: \n");
  scanf("%c",&in);
   
  while (in != 'q')
  {
    s[count++] = in;
    scanf("%c", &in);
  }
  printf("%d", count);
  printf("%s" , s);

Input:

    sam 

    tam 

    q

Output:

    9����

I don't understand how can I store strings at an individual index of array and why is count giving me wrong value when it should have been 2.

Is there any other method to store string using while loop?


Solution

  • The problem is you're scanning a single character instead of a string. tam and sam are 3 characters, not one. You would need to modify your code to something like this which reads the input string into an input buffer and then copies it to the s buffer you have.

    Edit: Sorry I misunderstood your question. This should do what you're wanting. Let me know if you have any questions about it.

    #include <stdio.h> // scanf, printf
    #include <stdlib.h> // malloc, free
    #include <string.h> // strlen, strcpy
    
    #define MAX_NUM_INPUT_STRINGS 20
    
    int main(int argc, char **argv) { // Look no further than our friend argv!
        char* s[MAX_NUM_INPUT_STRINGS], in[100]; // change in to buffer here, change s to char pointer array
        size_t count = 0, len;
        printf("Enter individual names: \n");
        do {
            scanf("%s",in);
            size_t len = strlen(in);
            if (in[0] == 'q' && len == 1) {
                break;
            }
            // allocate memory for string
            s[count] = malloc(len + 1); // length of string plus 1 for null terminating char
            s[count][len] = '\0'; // Must add null terminator to string.
            strcpy(s[count++], in); // copy input string to c string array
        } while (count < MAX_NUM_INPUT_STRINGS); // allows user to enter single char other than 'q'
        printf("Count: %lu\n", count);
        for (size_t i = 0; i < count; i++) {
            printf("%s\n", s[i]);
        }
    
        // free allocated memory
        for (size_t i = 0; i < count; i++) {
            free(s[i]);
        }
        return 1;
    }