+2

How to take input like this. Take N no of string values

Input: 3 Orange blue red int main(){ int a; char str[100]; scanf("%d\n",&a); for(int i=0;i<a;i++){ scanf("%s",&str[i]); }

c

8/18/2019 5:58:40 PM

Geek

1 Answer

New Answer

+3

Geek For reading 3 strings you need a 2D array if you want to store the strings. For display purpose a 1D array of char is enough char str[3][100]; for(int i=0; i<a; i++) { scanf("%s", str[i]); // if you want to store } The way you are doing it is overwriting the data of previous string. // for read and print only char str[100]; for(int i=0; i<a; ++i) { scanf("%s", str or &str[0]); puts(str); } Since you are reading the number of strings to read from user, ideally you need char **str (a pointer to a pointer to char) then read no of strings to read. Allocate memory for that many strings str = (char**)malloc(a * sizeof(char*)); for(int i=0; i<a; ++i) { str[i] = (char*)malloc(100*sizeof(char));//a string of max 100 chars scanf("%s", str[i]); } later free the memory for(int i=0; i<a; ++i) { free(str[i]); } free(str); or you can declare an array of pointers to char char *str[100]; // max of 100 strings. then read the strings for(int i=0; i<a; ++i){ str[i] = (char*)malloc(100 * sizeof(char)); // each string is of max 100 chars scanf("%s", str[i]); } // later free the memory for(int i=0; i<a; ++i){ free(str[i]); }