-1

I am writing a C program to generate userid's from a given file (users). The file has each user's first and last names each line (eg. "John Smith", "Steve Mathews" etc). The following while loop reads each line from users and prints in the console in all lowercase. In this case, single_line holds names in lower case.

while(!feof(fp)) {
        fgets(single_line, 80, fp);
        for(int i = 0; single_line[i]; i++){
          single_line[i] = tolower(single_line[i]);
        }
        char f_letter = single_line[0];
        char r_letters[20];
}

Now, I want to create a username for each single_line with the first letter of the first name and remaining letters of last name. So far, f_letter holds the first letter of first name, how can I make r_letters hold the remaining letters of last name?

Naz Islam
  • 409
  • 1
  • 6
  • 20

3 Answers3

1

You can use strtok to extract tokens from strings using a delimiter.

For example, for a line of text read from a file using fgets (assuming each line only contains two words, as is your case), you can extract the first and second words as:

char *first_name = strtok(single_line, " ");
char *last_name = strtok(NULL, "\n");

newline character is used as the second delimiter because fgets preserves it when reading a line, so it can be used to extract the last token before the newline.

Consider the following function for creating usernames:

#include <stdio.h>
#include <string.h>

void create_usernames(char *filename) {
    char line[80], username[80];
    char *last;
    FILE *fp = fopen(filename, "r");
    // fgets returns a NULL pointer upon EOF or error
    while (fgets(line, 80, fp) != NULL) {
        last = strtok(line, " ");
        last = strtok(NULL, "\n");
        printf("%c%s\n", line[0], last);
    }
    fclose(fp);
}

For example, with a file file.txt containing names:

John Smith
John Diggle
Bruce Wayne
Steve Mathews

you would have:

create_usernames("file.txt");
JSmith
JDiggle
BWayne
SMathews
assefamaru
  • 2,751
  • 2
  • 10
  • 14
1
char first_name[81];
char last_name[81];
char user_name[82];
while(!feof(fp)) {
        if(fscanf(fp, "%80s %80s", first_name,last_name) == 2){

            for(i = 0; i < strlen(first_name); i++){
              first_name[i] = tolower(first_name[i]);
            }
            for(i = 0; i < strlen(last_name); i++){
              last_name[i] = tolower(last_name[i]);
            }

            sprintf(user_name, "%c%s", first_name[0], last_name);
        }
}
aes
  • 46
  • 3
0

find the index of the space between the first and last name, say j. the index of the first letter of the last name would be j+1.

jumpnett
  • 6,967
  • 1
  • 19
  • 24