#include #include /* macro to define length of a city name */ #define N 20 int main (void) { char city[N], city2[N]; printf("Example 1: we read strings using scanf\n"); printf ("What is the capital of Canada? "); /* the string is read with the %s placeholder */ /* do not use & at front of the array name */ scanf("%s", city); printf("What is the capital of Argentina? "); scanf("%s", city2); printf("\nHere is the report about what was read\n"); printf("\nThe capital of Canada is: %s.", city); printf("\nThe capital of Argentina is: %s.", city2); printf("\n"); printf("\nExample 2: we read strings using gets\n"); printf("Warning: the gets function is dangerous and should not be used\n\n"); printf ("What is the capital of Canada?"); gets(city); printf("What is the capital of Argentina?"); gets(city2); printf("\nHere is the report about what was read\n"); printf ("\nThe capital of Canada is: %s.", city); printf ("\nThe capital of Argentina is: %s.", city2); printf("\n"); printf("\nExample 3: we read strings using fgets(name,size,stdin)\n"); printf("Warning: fgets keeps the new-line symbol at the end\n"); printf ("What is the capital of Canada? "); fgets(city,sizeof(city),stdin); printf("What is the capital of Argentina? "); fgets(city2,sizeof(city2),stdin); printf("\nHere is the report about what was read\n"); printf ("\nThe capital of Canada is: %s.", city); printf ("\nThe capital of Argentina is: %s.", city2); printf("\n"); printf("\nExample 4: we read strings using fgets(name,size,stdin)\n"); printf("We will replace the new-line symbol with the null symbol\n"); printf ("What is the capital of Canada? "); /* the string is read with fgets */ fgets (city, sizeof(city), stdin); printf ("What is the capital of Argentina? "); fgets (city2, sizeof(city2), stdin); /* fgets keeps \n at the end, replace it with \0 */ /* Recall that the strlen function returns the length of the string not counting the null character. */ city[strlen(city)-1] = '\0'; city2[strlen(city2)-1] = '\0'; /* here is the report */ printf("\nHere is the report about what was read\n"); printf ("\nThe capital of Canada is: %s.", city); printf ("\nThe capital of Argentina is: %s.\n", city2); return (0); }