how to use getchar() to store n names in an array ?
-
i am trying to take multiple names by using getchar() but it only taking the first value and just skipping the rest. here is the code.
#include int main()
{
char name[10][30], ch;
int i;for(i=0; i<10; i++) { printf("Enter name: \\n"); int j=0; while(ch != '\\n') { ch = getchar(); name\[i\]\[j\] = ch; j++; } name\[i\]\[j\] = '\\0'; } return 0;
}
-
i am trying to take multiple names by using getchar() but it only taking the first value and just skipping the rest. here is the code.
#include int main()
{
char name[10][30], ch;
int i;for(i=0; i<10; i++) { printf("Enter name: \\n"); int j=0; while(ch != '\\n') { ch = getchar(); name\[i\]\[j\] = ch; j++; } name\[i\]\[j\] = '\\0'; } return 0;
}
Because at the end of the first time round the
while
loopch
will contain the newline character, so every other loop will terminate immediately. You must remember to reset variables after you have finished with them. Please get yourself a good study guide on C and learn the language the proper way. -
i am trying to take multiple names by using getchar() but it only taking the first value and just skipping the rest. here is the code.
#include int main()
{
char name[10][30], ch;
int i;for(i=0; i<10; i++) { printf("Enter name: \\n"); int j=0; while(ch != '\\n') { ch = getchar(); name\[i\]\[j\] = ch; j++; } name\[i\]\[j\] = '\\0'; } return 0;
}
-
In addition to what Richard wrote, you have limited the names to 30 characters so make sure more than that are not entered.