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!
11 Respostas
+ 5
Use one for loop and in inner part of loop write scanf and use %s
+ 3
for (int i=0; i<4; i++) scanf("%s", &string[i]);
+ 2
Jia Yin &string[i] is wrong. Try scanf("%s", string[i]);
+ 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;
}
+ 1
SapphireBlue you are right... sorry... đ
0
c or c++?
0
Its C language
0
for (int i=0; i<4; i++) scanf("%s", &string[i]);
I tried, but it wasnt work.
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.
- 1
pls help.