简体   繁体   中英

alternatives to strcpy in ISO C89

I have to write a function for a phonebook. I have defined the phonebook as an array of struct "contacts",each struct contact containing the name[],surname[],number,[]address[] strings,which are also the parameters of the function. The problem is that when I have to save the entered parameters in the position "count" of the phonebook array(ie phonebook[count].name) VS 2010 said I can't use "=" to save the string into the array. On the internet some people said that I can use pointers or strcpy,but my teacher doesn't want me to use them. Are there some alternatives? I have to code in ISO C89(ANSI C) and I can use the string.h and ctype.h libraries (I can't use strcpy or strcat),and I can't use files or pointers. I'm not sure about strncpy,anyway.

A simple character-by-character assignment will work.

#include <stdio.h>

#define BUFFER_LENGTH 128

struct contacts {
    char name[BUFFER_LENGTH];
    char surname[BUFFER_LENGTH];
    char number[BUFFER_LENGTH];
    char address[BUFFER_LENGTH];
};

int main(void) {
    struct contacts phonebook[1];
    int count = 0;
    char parameter[BUFFER_LENGTH];
    int i;

    /* enter some parameter */
    for (i = 0; i < BUFFER_LENGTH - 1; i++) {
        int input = getchar();
        if (input == '\n' || input == EOF) break;
        parameter[i] = input;
    }
    parameter[i] = '\0';

    /* save it to the array */
    for (i = 0;; i++) {
        if ((phonebook[count].name[i] = parameter[i]) == '\0') break;
    }

    /* print the saved parameter for checking */
    puts(phonebook[count].name);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM