Search code examples
cgetchar

using getchar() in c getting Segmentation fault (core dumped)


I'm writing a program which requires me to enter a series of char which are loaded into a char array to be used later. The code I am trying to get to work looks like:

char temp = getchar();
while(temp != '\n'){//input char into temp until '\n'
    input[strlen(input)] = temp;//adds temp to end of input
    temp = getchar();
}

but when I get to this line in the program I get "Segmentation fault (core dumped)" and crashes.. When I replace the \n with another char, for example %

char temp = getchar();
while(temp != '%'){//input char into temp until '\n'
    input[strlen(input)] = temp;//adds temp to end of input
    temp = getchar();
}

then it works fine, but I want to use the newline and not %. I've looked on several tutorials and they said this is how to input until enter is hit so I'm not sure what the problem is. Thanks in advance.


Solution

  • You can use this :

    while ( (temp=getchar()) != EOF && temp != '\n' )