Computer Science, asked by ak9701849, 1 year ago

What are the two ways of reading a string array? Explain by talking an example of reading a string "hello world"?

Answers

Answered by krishasingh17
1
Use:

fgets (name, 100, stdin);

100 is the max length of the buffer. You should adjust it as per your need.

Use:

scanf ("%[^\n]%*c", name);

The [] is the scanset character. [^\n]tells that while the input is not a newline ('\n') take input. Then with the %*c it reads the newline character from the input buffer (which is not read), and the *indicates that this read in input is discarded (assignment suppression), as you do not need it, and this newline in the buffer does not create any problem for next inputs that you might take.

Read here about the scanset and the assignment suppression operators.

Note you can also use gets but ....

I hope this helps you.
Answered by garywalter1221
2

First method

#include <stdio.h>  

int main()  

{  

  char str[10];  

  gets(str);  

  printf("%s", str);  

  return 0;  

}


Second method


#include <stdio.h>  

#define NUM 20  

int main()  

{  

  char str[NUM];  

  fgets(str,NUM, stdin);  

  printf("%s", str);  

 

  return 0;  

}


Third method

#include <stdio.h>  

int main()  

{  

  char str[10];  

  scanf("%[^\n]%*c", str);  

  printf("%s", str);  

 

  return 0;  

}


Similar questions