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

标签 c arrays variables strtok

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

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 '\0'
    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]);
}

关于c - 如何将一个字符保存到多个变量中? C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40710413/

相关文章:

javascript - 在 LazyJS 中的哪个位置

arrays - 使用多个索引 :[Int] 枚举多线性映射的 Swift 算法

linux - Perl 脚本,如何从 .bash_profile 获取环境变量

c - 如何制作可 Bootstrap ?

c - 何时/何处分配本地数组?

python - 获取 'TypeError: ' 列表“对象不可调用”错误

linux - 如何在 shell 脚本中回显动态变量的内容

android - 在android中使用静态变量

c - 无法使用 C 编译器打开包含文件 "Protocols.h"

java - 在 Linux 终端中编译项目不起作用