user3522013
user3522013

Reputation: 13

Scanning in strings into a 2D array in C

I need to take an input of 20 words entered by the user put those into a 2D array and print that out my current code is

char array2[20][20];
int i;
for(i=0;i<20;i++)
{
    printf("enter a word\n");
    scanf(" %[^\n]",array2[i]);
}

for(i=0;i<colsize2;i++)
{
    printf("\n");
    for(j=0;j<rowsize2;j++)
    {
        printf("%c",array2[i][j]);
    }
}

(I have no idea what %[^\n] is but it works better than %c or %s)

there are no compiler errors and the program will run but when it prints the array after all the words have been entered all I get is complete garbage

like

aȪ(M▒awn-US▒ e▒(<▒▒t/▒▒▒(5h▒tr:▒( qh▒tdle__000 HW5.exe▒`wauld▒(▒&Oe,▒*a▒+a▒▒

so much so that it takes a bit of scrolling to get back to the start of my program

I do have more in this program that's not in my question but I'm 99% sure it wouldn't mess with what I have here but if you do want to see the rest just ask

I literally just started programming so I don't know diddly squat about it yet so if you could keep that in mind when you answer also this is for a school assignment so it doesn't need to be perfect it just has to get the job done

thanks to whoever answers this I've been grappling with this for hours

Upvotes: 1

Views: 8670

Answers (2)

ajay
ajay

Reputation: 9680

The format string

" %[^\n]" 
 ^ note the leading space

means that scanf will first read and discard any number of leading whitespace characters and then match any sequence of characters which does contain a newline. scanf can potentially overrun the buffer it save the string into if the input string is too large for the buffer invoking undefined behaviour. The %s format specifier means scanf skips the leading whitespace characters and reads the input string till it encounters a whitespace at which point it appends a terminating null byte to the buffer it writes into and then returns.

Therefore, what you need is

char array2[20][20];
int i;

for(i = 0; i < 20; i++)
    scanf("%19s", array2[i]);

for(i = 0; i < 20; i++)
    printf("%s\n", array2[i]);

Upvotes: 1

this
this

Reputation: 5290

Initialize your array to 0:

char array2[20][20] = { 0 } ;

And then print the string not every character:

for(i=0;i<20;i++)
{
    printf("%s",array2[i]);
    printf("\n");
}

Upvotes: 0

Related Questions