1
votes

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?

Thankyou so much.

2

2 Answers

1
votes

C-strings need a '\0' at the end and you not adding one to s.

printf("%d", count);
s[count] = '\0'; // ADD THIS LINE
printf("%s" , s);

But you could alternatively read as follows:

char s[100];
scanf("%99[^q]" s); // Will read up to 99 chars that are not a 'q'
printf("%s\n", s);
int count = strlen(s);
1
votes

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;
}