// Example program #2 from Chapter 19 of Absolute Beginner's Guide
// to C, 3rd Edition
// File chap19ex2.c
// Osman Zakir
// 11 / 23 / 2016
/* This program asks a user for their hometown and the two-letter
abbreviation of their home state. It then uses string concatenation
to build a new string with both town and state and prints it using
puts. */
#include <stdio.h>
#include <string.h>
int main()
{
char city[15] = "", st[3] = "";
puts("What town do you live in? ");
fgets(city, strlen(city), stdin);
int ch;
while (((ch = fgetc(stdin)) != '\n') && (ch != EOF));
puts("What state do you live in? (2-letter abbreviation) ");
fgets(st, strlen(st), stdin);
while (((ch = fgetc(stdin)) != '\n') && (ch != EOF));
char fullLocation[18] = "";
strcpy(fullLocation, city);
strcat(fullLocation, ", ");
strcat(fullLocation, st);
puts("You live in ");
fputs(fullLocation, stdout);
return 0;
}
How do I fix this? What am I missing? Thanks in advance (note: I'm trying to use TDM-GCC to compile this on the MinGW Command Prompt. Using LLVM Clang, I can't compile it if I use gets (plus I have to be using the VS2015 Developer Command Prompt)).
// Example program #2 from Chapter 19 of Absolute Beginner's Guide
// to C, 3rd Edition
// File chap19ex2.c
// Osman Zakir
// 11 / 23 / 2016
/* This program asks a user for their hometown and the two-letter
abbreviation of their home state. It then uses string concatenation
to build a new string with both town and state and prints it using
puts. */
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <string.h>
int main()
{
char city[15] = "", st[3] = "";
puts("What town do you live in? ");
fgets(city, sizeof(city), stdin);
fflush(stdin);
puts("What state do you live in? (2-letter abbreviation) ");
fgets(st, sizeof(st), stdin);
fflush(stdin);
char fullLocation[18] = "";
strcpy(fullLocation, city);
strcat(fullLocation, ", ");
strcat(fullLocation, st);
puts("You live in ");
fputs(fullLocation, stdout);
return 0;
}
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.