0

HELP!!!

char *string[]={“dog”,”ant”,”cat”,”elephant”}; instead of using declaration like above, may i know how can i get user input for strings of character? Thanks for helping!

16th Jun 2020, 3:27 AM
Jia Yin
Jia Yin - avatar
11 Respuestas
+ 5
Use one for loop and in inner part of loop write scanf and use %s
16th Jun 2020, 8:16 AM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 3
for (int i=0; i<4; i++) scanf("%s", &string[i]);
16th Jun 2020, 3:50 AM
Bilbo Baggins
Bilbo Baggins - avatar
16th Jun 2020, 11:53 AM
SapphireBlue
SapphireBlue - avatar
+ 2
Jia Yin &string[i] is wrong. Try scanf("%s", string[i]);
18th Jun 2020, 1:42 PM
SapphireBlue
SapphireBlue - avatar
+ 1
You need a multidimension char array to store user inputs. char pointer (char*) are constant and non write-able. #include <stdio.h> int main() { char animals[4][20]; // 4 rows @ 20 char each for(size_t i = 0; i < 4; i++) { printf("Enter animal %lu > ", i + 1); fflush(stdout); // read up to 19 char. Leave the last // character as string terminator. scanf("%19s", animals[i]); } for(size_t i = 0; i < 4; i++) { printf("Animal %lu > %s\n", i + 1, animals[i]); } return 0; }
16th Jun 2020, 5:42 AM
Ipang
+ 1
SapphireBlue you are right... sorry... 🙄
18th Jun 2020, 5:42 PM
Bilbo Baggins
Bilbo Baggins - avatar
0
c or c++?
16th Jun 2020, 4:08 AM
durian
durian - avatar
0
Its C language
16th Jun 2020, 5:13 AM
Jia Yin
Jia Yin - avatar
0
for (int i=0; i<4; i++) scanf("%s", &string[i]); I tried, but it wasnt work.
16th Jun 2020, 5:13 AM
Jia Yin
Jia Yin - avatar
0
Jia Yin You cannot do that for char *string[] = { . . . } since that's an array of pointers to read-only memory. You need a sized buffer to store the characters from stdin. char string[4][32]; for (int i = 0; i < 4; i++) scanf("%31s", string[i]); I would also recommend using fgets() over scanf(). The scanf() functions have a whole range of issues that make them a poor choice for user input. If you're going to use it, at least make sure it doesn't go past the string buffer by defining the width in the format specifier.
16th Jun 2020, 5:41 AM
Gen2oo
Gen2oo - avatar
- 1
pls help.
16th Jun 2020, 3:30 AM
Jia Yin
Jia Yin - avatar