In: Computer Science
Modify the program so that after it reads the line typed on the keyboard, it replaces the ‘\n’ character with a NUL character. Now you have stored the input as a C-style string, and you can echo it with: Explain what you did. #include <unistd.h> #include <string.h> int main(void) { char aString[200]; char *stringPtr = aString; write(STDOUT_FILENO, "Enter a text string: ", strlen("Enter a text string: ")); // prompt user read(STDIN_FILENO, stringPtr, 1); // get first character while (*stringPtr != '\n') // look for end of line { stringPtr++; // move to next location read(STDIN_FILENO, stringPtr, 1); // get next character } // now echo for user write(STDOUT_FILENO, "You entered:\n", strlen("You entered:\n")); stringPtr = aString; do { write(STDOUT_FILENO, stringPtr, 1); stringPtr++; } while (*stringPtr != '\n'); write(STDOUT_FILENO, stringPtr, 1); return 0; }
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
#include <unistd.h>
#include <string.h>
int main(void)
{
char aString[200];
char* stringPtr = aString;
write(STDOUT_FILENO, "Enter a text string: ",
strlen("Enter a text string: ")); // prompt user
read(STDIN_FILENO, stringPtr, 1); // get first character
while (*stringPtr != '\n') // look for end of line
{
stringPtr++; // move to next location
read(STDIN_FILENO, stringPtr, 1); // get next character
}
//right now stringPtr is pointing to the location on array that contain \n character, so
//replacing '\n' character with null terminator '\0' to indicate end of string
*stringPtr = '\0';
write(STDOUT_FILENO, "You entered:\n",
strlen("You entered:\n"));
//now simply printing aString. the strlen method returns the number of characters found
//before the end of string. in c strings, null terminator or \0 indicate end of string,
//so the system returns the count of characters upto \0, and those characters will be printed.
write(STDOUT_FILENO, aString, strlen(aString));
//uncomment below line if you want to print a newline after the string.
//write(STDOUT_FILENO, '\n', 1);
return 0;
}
/*OUTPUT*/
Enter a text string: hello world
You entered:
hello world