How do I enter a string into a 2d array in C?

If I want to take input into a 2d array with each line on one line and another on the other (i.e. change the line when hitting enter). How can I do this in C. C doesn't seem to have a convenient handling of "String". I obviously mean to do this without using getchar ().

+2


source to share


3 answers


#include<stdio.h>

main()

{

char student_name[5][25];

    int i;

    for(i=0;i<5;i++)
    {
       printf("\nEnter a string %d: ",i+1);
       scanf(" %[^\n]",student_name[i]);
    }

}

      



u can read lines using a 2d array without using getchar () by putting a space in scanf ("% [^ \ n]"); up to% [^ \ n]!

+3


source


There are 3 ways which are mentioned below.

If you know the maximum number of lines and the maximum number of characters, you can use the method below to declare a character array.

char strs[MAX_NO_OF_STRS][MAX_NO_CHARS] = {0};
for (i = 0; i < MAX_NO_OF_STRS; i++)
{
    scanf("%s", strs[i]);
}

      

If you know the maximum number of lines and you don't want to waste memory allocating memory MAX_NO_CHARS

for all lines. then go to array of char pointers.



char temp[MAX_NO_CHARS] = {0};
char *strs[MAX_NO_OF_STRS] = NULL;
for (i = 0; i < MAX_NO_OF_STRS; i++)
{
    scanf("%s", temp);
    strs[i] = strdup(temp);
}

      

If you know the maximum number of lines at runtime, you can declare a double pointer char

. Get the number of rows n

from the user and then allocate the memory dynamically.

char temp[MAX_NO_CHARS] = {0};
char **strs = NULL;
int n = 0;
scanf("%d", &n);
strs = malloc(sizeof(char*) * n);
for (i = 0; i < n; i++)
{
    scanf("%s", temp);
    strs[i] = strdup(temp);
}

      

+3


source


An alternative to using malloc

and filling an array of pointers with fixed-size buffers would be to allocate a 2d array (in static storage or on the stack) and fill it. An example of modified KingsIndian code would look something like this:

#include <stdio.h>

int main()
{
 char str[2][256] = {{0}};
 int i = 0;

  for(i=0;i<2;i++)
  {
    scanf("%255s", &str[i][0]);
  }
  return 0;
}

      

If all the strings you expect to receive are no larger than a certain size, then this approach will save you the trouble of freeing memory yourself. However, it is less flexible, which means that you cannot fit the size of an individual buffer to the string it contains.

EDIT

Adding to the information in the comments, we read a line that only ends with a newline, not any space:

scanf("%255[^\n]", str[i]);

      

0


source







All Articles