From 3d602be8f5e8897322b07c6d92d6ec26cd59aa7e Mon Sep 17 00:00:00 2001 From: Jack-Benny Persson Date: Wed, 14 Oct 2015 02:26:35 +0200 Subject: [PATCH] Starting tinkering with text --- vagen_till_c/ch2/text1.c | 10 ++++++++++ vagen_till_c/ch2/text2.c | 23 +++++++++++++++++++++++ vagen_till_c/ch2/text2_safer.c | 27 +++++++++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 vagen_till_c/ch2/text1.c create mode 100644 vagen_till_c/ch2/text2.c create mode 100644 vagen_till_c/ch2/text2_safer.c diff --git a/vagen_till_c/ch2/text1.c b/vagen_till_c/ch2/text1.c new file mode 100644 index 0000000..0dde580 --- /dev/null +++ b/vagen_till_c/ch2/text1.c @@ -0,0 +1,10 @@ +#include + +int main() +{ + char name[20]; + printf("Enter your name: "); + // scanf("%s", name); // Unsafe since name is limited to 20 characters + scanf("%19s", name); // Much safer + printf("Hello %s\n", name); +} diff --git a/vagen_till_c/ch2/text2.c b/vagen_till_c/ch2/text2.c new file mode 100644 index 0000000..22a4b47 --- /dev/null +++ b/vagen_till_c/ch2/text2.c @@ -0,0 +1,23 @@ +#include + +/* Instead of scanf we use getchar to be able to read the entire name, including + * spaces in between first- and lastname. + */ + +int main() +{ + char name[20], c; + int i; + + printf("Enter your name: "); + i = 0; // Start with i = 0 for name + while ((c = getchar()) != '\n') // Get characters for as long as it's not a + { // newline character. + name[i] = c; // For each loop, put 'c' into name[i] where + i++; // 'i' is it's current position, increase i + } // for each itteration. + name[i] = '\0'; // Then put a '\0' character at the end of + printf("Hello %s\n", name); // name to declare end of text. + + return 0; +} diff --git a/vagen_till_c/ch2/text2_safer.c b/vagen_till_c/ch2/text2_safer.c new file mode 100644 index 0000000..8c1fb5a --- /dev/null +++ b/vagen_till_c/ch2/text2_safer.c @@ -0,0 +1,27 @@ +#include + +/* Instead of scanf we use getchar to be able to read the entire name, including + * spaces in between first- and lastname. + */ + +int main() +{ + char name[20], c; + int i; + + printf("Enter your name: "); + i = 0; // Start with i = 0 for name + while ((c = getchar()) != '\n') // Get characters for as long as it's not a + { // newline character. + name[i] = c; // For each loop, put 'c' into name[i] where + i++; // 'i' is it's current position, increase i + if ( i >= 19 ) // for each itteration. + { + break; // If we exceed 19 characters, break out of + } // loop to avoid overflow. + } + name[i] = '\0'; // Then put a '\0' character at the end of + printf("Hello %s\n", name); // name to declare end of text. + + return 0; +}