The guy gave you confusing advice:
#include <conio.h>
is non standard and non portable.
scanf("%s", str);
is a security flaw: if you type more than 99 letters, you will cause a buffer overrun with undefined behavior. Either use scanf("%99s", str);
to read a single word or fgets(str, sizeof str, stdin);
to read a full line of input.
scanf("\n");
will skip any whitespace. Hitting enter will not suffice, you will need to type a non blank character, which will be read by the next scanf()
or other input operation.
fflush(stdin)
has undefined behavior. If you want to read the rest of the current input line, use int c; while ((c = getchar()) != EOF && c != '\n') continue;
scanf("%[^\n]%*c", str2);
has a security flaw, just like the previous case.
getch()
is non portable. Just use getchar()
after reading the rest of the pending line.
Here is a modified version using scanf()
:
#include <stdio.h>
int main() {
char str[100] = "", str2[100] = "";
int c;
printf("Enter a string: ");
scanf("%99[^\n]", str);
while ((c = getchar()) != EOF && c != '\n')
continue;
printf("Enter a string2: ");
scanf("%99[^\n]", str2);
while ((c = getchar()) != EOF && c != '\n')
continue;
printf("string 1: %s\n", str);
printf("string 2: %s\n", str2);
getchar(); // prevent legacy system from closing terminal window
return 0;
}
Here is a simpler version using fgets()
:
#include <stdio.h>
#include <string.h>
int main() {
char str[100] = "", str2[100] = "";
printf("Enter a string: ");
fgets(str, 100, stdin);
str[strcspn(str, "\n")] = '\0'; // strip the trailing newline if any
printf("Enter a string2: ");
fgets(str2, 100, stdin);
str2[strcspn(str2, "\n")] = '\0'; // strip the trailing newline if any
printf("string 1: %s\n", str);
printf("string 2: %s\n", str2);
getchar(); // prevent legacy system from closing terminal window
return 0;
}