0

Hi i am quite new into programming and i need some small help on converting char array to string and i am not sure where has gone wrong. i need to get user input in %c and i input for the first input - aabcc and then clicks on enter the second input - fsdff then enter again 3rd input - rewrr then enter again 4th input - zzxcc and enter again the last input - asdfg.

But the outputs gives me array 1 = aabcc , 2nd array = fsdf (one of gone missing) 3rd array = f '\n' ... followed by 3rd 4th and 5th array displayed incorrectly. Thanks all in advanced.

int main()
{
   int i, j;
char ch[5][6];
char c[5][5];

for (i = 0; i < 5; i++)
    for (j = 0; j<5; j++)
        scanf("%c", &c[i][j]); // get user input

memcpy(ch[0], c[0], 5);
ch[0][5] = '\0';
memcpy(ch[1], c[1], 5);
ch[1][5] = '\0';
memcpy(ch[2], c[2], 5);
ch[2][5] = '\0';
memcpy(ch[3], c[3], 5);
ch[3][5] = '\0';
memcpy(ch[4], c[4], 5);
ch[4][5] = '\0';

printf("array 1 = %s, array 2 = %s , array 3 = %s , array 4 = %s , array 5 = %s ", ch[0], ch[1], ch[2], ch[3], ch[4]);
}
2

2 Answers 2

1

Change below scanf

scanf("%c", &c[i][j]);

to

scanf(" %c", &c[i][j]);
       ^
       |
    space here

Reason behind it is, you are entering input as aabcc<Enter>, there are 6 characters in the input buffer. scanf("%c") reads the a, a, b, c and then c, interpreting them as the aabcc, but the newline character is still in the input buffer. Thats why you see newline as well when you try printing them.

Sign up to request clarification or add additional context in comments.

Comments

1

Your scanf buffer (c[][]) is too small to hold all the characters from a single entry. As another writer pointed out, you have not added space for the '\n' character in your static allocation.

The size of your scanf character array (c[][]) should be = max no. of words x (max no. of chars in a word + 1)

The plus one is for the newline character.

#define MAXWORDSIZE 5
#define MAXWORDS 10

char c[MAXWORDS][MAXWORDSIZE + 1];      // Newline character
char ch[MAXWORDS][MAXWORDSIZE + 1 + 1]; // Newline and NUL character

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.