-3

I try to get a text attached to the array but this does not seem to work when I try to use printf after. It does print a blank space.

char text[10][30];      // 10 is text count and 30 text length
printf("Enter text: ");
text[0]=getchar();
Stefi Zuzu
  • 35
  • 7

1 Answers1

1

Here is a possible solution to do what you want. Since your length is a fixed 30, fgets is a good candidate.

#include <stdio.h>

int
main(void)
{
    char text[10][30];

    printf("Input\n");

    fgets(text[0], sizeof(text[0]), stdin);

    printf("%s\n", text[0]);
}
Jake
  • 78
  • 7
  • Why ten rows in the matrix when only one is used? It would be better to use `char text[30];`. Also, it is sensible to use `fgets(text[0], sizeof(text[0]), stdin);` if you keep the current definition. And the return value from `fgets()` should be checked before the data is used. – Jonathan Leffler Mar 20 '18 at 16:01
  • @JonathanLeffler I am just trying to use as much of his initial code as possible. I'm assuming there was a reason he wanted 10 strings. You are correct in using sizeof and checking the return value. I didn't want to open up another can of worms for OP. – Jake Mar 20 '18 at 16:05
  • 1
    What you can do (what I tend to do) is keep close to the original code, but comment on some of the things that should be changed. The test for valid input is more nearly critical — I'd make that change anyway: `if (fgets(text[0], sizeof(text[0]), stdin) != NULL) printf("%s\n", text[0]);`. If the input is short enough, there'll be two newlines in the output; I probably wouldn't bother to mention that. – Jonathan Leffler Mar 20 '18 at 16:08