I want to create a program that opens and writes to 3 different text files, the names a user inputs.
The condition would be that if last names end with certain characters, they would be saved to a specific text file.
For example, if the user inputs a last name that ends with ian
it should be saved to the ARMENIA.TXT
folder.
Here is my code and the issues I encounter with it:
struct names {
char firstName[20];
char lastName[30];
} person;
int main() {
FILE *arm, *ita, *esp;
char ian[] = "ian";
char ini[] = "ini";
char ez[] = "ez";
char response;
char *ret;
arm = fopen("C:\\Programming\\ARMENIA.TXT", "wt");
ita = fopen("C:\\Programming\\ITALIA.TXT", "wt");
esp = fopen("C:\\Programming\\ESPANIA.TXT", "wt");
if (arm, ita, esp == NULL) {
printf("Error: The archives could not be created.");
return 1;
} else {
printf("Operation Successful: Archives created.\n\n");
}
do {
fflush(stdin);
printf("\n\nPlease input your first name: ");
scanf("%s", &person.firstName);
printf("Please input your last name: ");
scanf("%s", &person.lastName);
if (ret = strstr(person.lastName, ian)) {
fwrite(person.lastName, 1, strlen(person.lastName), arm);
fwrite(person.firstName, 1, strlen(person.firstName), arm);
}
if (ret = strstr(person.lastName, ini)) {
fwrite(person.lastName, 1, strlen(person.lastName), ini);
fwrite(person.firstName, 1, strlen(person.firstName), ini);
}
if (ret = strstr(person.lastName, ez)) {
fwrite(person.lastName, 1, strlen(person.lastName), ez);
fwrite(person.firstName, 1, strlen(person.firstName), ez);
}
printf("\n\nWould you like to enter another person into the archive?: (y) or (n): ");
scanf(" %c", &response);
} while (response == 'y');
printf("\n\nThe operation has finished.\n\n");
fclose(arm);
fclose(ita);
fclose(esp);
return 0;
}
Issue: Will save to folder if last name contains ian
(or ini
/ ez
) in ANY part of the last name. How do I make the condition only if it ENDS with these strings?
Issue: Will crash if last name contains ini
or ez
-- basically, only first If statement works.
Issue: Needs to be saved as Lastname, Firstname -- For now, it saves as LastnameFirstname.