如何将一个字符保存到多个变量中? C

How can I save a char into multiple variables ? C

好的,所以我需要输入这样的字符串

IP_1/MASK IP_2 NUM [NET_1 NET_2 NET3 ... NET_NUM]

例如:

192.168.25.87/24 192.168.26.1 3 192.168.0.0/16 192.0.26.0/16 192.168.26.0/24

然后将此字符串拆分为多个变量(IP_1MASK 等)。 我在互联网上遵循了如何拆分它的指南,我是这样做的:

int main()
{
    char* IP_1[256],IP_2[256],NET[256][256],character[256];
    int MASCA,NUM,i=1,j;
    char *p;
    gets(character);
    p=strtok(character,"/ ");
    while(p!=NULL)
    {
        printf("%s\n",p);
        p=strtok(NULL,"/ ");
    }

所以,这样做我将数组拆分为多个元素,但是如何将这些元素保存到 IP_1MASK IP_2NUM NET_1 等...?

有很多方法。
例如,进行如下操作。

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

int main(void){
    char IP_1[256], IP_2[256], NET[256][256], line[256], rest[256];
    int MASK, NUM, i;
    char *p;

    fgets(line, sizeof line, stdin);//gets has already been abolished.
    //Since the first three elements are fixed, use sscanf
    if(3 > sscanf(line, "%s %s %d %255[^\n]%*c", IP_1, IP_2, &NUM, rest)){
        printf("invalid input\n");
        return -1;
    }
    if(NULL==(p = strchr(IP_1, '/'))){
        printf("invalid input\n");
        return -1;
    }
    *p = 0;// Replace '/' with '[=10=]'
    MASK = atoi(p + 1);// convert next '/' to int

    for(p=strtok(rest, " \n"), i = 0; i < NUM && p; ++i, p=strtok(NULL, " \n")){
        strcpy(NET[i], p);//strtok and copy
    }
    //test print
    printf("IP_1:%s\n", IP_1);
    printf("MASK:%d\n", MASK);
    printf("IP_2:%s\n", IP_2);
    for(i = 0; i < NUM; ++i)
        printf("NET_%d:%s\n", i + 1, NET[i]);
}