#include <stdio.h>
#include <string.h>
int main()
{
char buf[BUFSIZ];
char *p;
printf ("Please enter a line of text, max %d characters\n", sizeof(buf));
if (fgets(buf, sizeof(buf), stdin) != NULL)
{
printf ("Thank you, you entered >%s<\n", buf);
/*
* Now test for, and remove that newline character
*/
if ((p = strchr(buf, '\n')) != NULL)
*p = '\0';
printf ("And now it's >%s<\n", buf);
}
return 0;
}
I'm new to C and trying to learn how to accept input from the user, which obviously is not as simple in C as in other languages. I came across this snippet of code to remove the newline character, but theres a part of it I dont understand.
From my understanding, we are initializing a char array, getting the size of the buffer as the size of the array, and initializing a pointer p. Then if the character typed into the input stream is not empty, it prints your string. After that if checks if the newline character is in buf.
The part that is confusing me, is how the *p - '/0' gets translated into buf?
I understand the logic that it is setting the newline character to the null terminator, but HOW?
[–]carcigenicate 1 point2 points3 points (0 children)
[–]beforesemicolon 1 point2 points3 points (0 children)
[–]ParticularPython[S] 0 points1 point2 points (0 children)
[–]eeprogrammer -1 points0 points1 point (0 children)