处理stdin输入的字符串指令

/* 处理不确定一行有多少个参数的指令
处理数字
输入:
2 3 44
输出:
2|3|44|

处理字符
输入:
a b s f
输出:
a|b|s|f|

处理字符串(当前处理方式!!!只是把input3中每个字符串的首地址赋值给char *str[128],且原本的input3数据已经改变,分割符的字符替换为'\0'。如果需要存储这些字符串,则需要一开始就给char *str[128]分配新的内存空间或者直接用字符数组接收)
输入:
asdf fgs ges
输出:
asdf|fgs|ges| 

处理:不断获取stdin的输入,直到遇到ctrl+c
*/


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

int main() 
{
    // 处理数字
    int num[128] = {0};
    int len_num = 0;

    char input1[128] = {0};
    fgets(input1, 128, stdin);
    char* token1 = strtok(input1, " \n");
    while (token1 != NULL)
    {
        num[len_num++] = atoi(token1);
        token1 = strtok(NULL, " \n");
    }
    for (int i = 0; i < len_num; i++)
    {
        printf("%d!", num[i]);
    }
    printf("\n");



    // 处理字符
    char ch[128] = {0};
    int len_ch = 0;

    char input2[128] = {0};
    fgets(input2, 128, stdin);
    char* token2 = strtok(input2, " \n");
    while (NULL != token2)
    {
        ch[len_ch++] = token2[0];
        token2 = strtok(NULL, " \n");
    }
    for (int i = 0; i < len_ch; i++)
    {
        printf("%c!", ch[i]);
    }
    printf("\n");

    // 处理字符串(当前处理方式!!!只是把input3中每个字符串的首地址赋值给char *str[128],且原本的input3数据已经改变,分割符的字符替换为'\0'。如果需要存储这些字符串,则需要一开始就给char *str[128]分配新的内存空间或者直接用字符数组接收)
    char *str[128] = {0};
    int len_str = 0;
    
    char input3[128] = {0};
    fgets(input3, 128, stdin);
    char* token3 = strtok(input3, " \n");  // 处理字符串时,strtok的delim需要带\n
    while (NULL != token3)
    {
        str[len_str++] = token3;
        token3 = strtok(NULL, " \n");
    }
    for (int i = 0; i < len_str; i++)
    {
        printf("%s!", str[i]);
    }
    printf("\n");

    // 不断获取stdin的输入,直到遇到ctrl+c
    char input4[128] = {0};
    while (fgets(input4, 128, stdin))
    {
        // 方式一:
        if (0 == strlen(input4))
        {
            break;
        }
        // 方式二:
        /* if (0 == strcmp("\0", input4))
        {
            break;
        } */
    }

    return 0;
}

 

posted @ 2024-04-21 23:58  jason8826  阅读(3)  评论(0编辑  收藏  举报