如何设置一个C函数,将用户输入分为多个部分,还可以将这些较小的部分也分成几个部分? [英] How to set up a C function that splits user input into multiple parts, and also splitting those smaller parts?

查看:38
本文介绍了如何设置一个C函数,将用户输入分为多个部分,还可以将这些较小的部分也分成几个部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开发一个C函数,该函数需要一行用户输入,例如以下行:

I'm trying to develop a C function that takes a line of user input, say example this line:

1X 1X 3Y 1Z 1Z 1Z 1Z 2X 2X

(这只是用户输入内容的任意示例.在实际程序中,他们可以输入1到48个数字字符对.)

( This is just an arbitrary example of what the user will enter. In the actual program, they can enter anywhere between 1 and 48 digit-character pairs.)

这个想法是,用户将插入整行,并将其分成9部分(每个数字和字符对是一部分).然后,数字和字符对也将彼此分开(我在考虑这一部分,它们都属于包含numValue和charValue的结构).

The idea is that the user will insert this entire line, and it will split it up into 9 parts (each number and character pair is one part). Then, the number and the character pair will also be split from each other (I'm thinking for this part, they will both belong to a struct containing a numValue and charValue).

我可以使用什么来拆分用户的输入?我是C的新手.

What can I use to split up the user's input? I'm relatively new to C.

推荐答案

可用于从用户中拆分输入字符串的函数是来自 #include<的 strtok().string.h> 库.这是一个示例,您可以用来将输入分为九部分.

A function you could use to split the input string from the user is strtok() from the #include <string.h> library. Here is an example you can you use to split the input into nine parts.

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

main (){
    char word[] ="1X 1X 3Y 1Z 1Z 1Z 1Z 2X 2X";
    int i = 0;
    char *p = strtok(word, " ");
    char *array[9];

    while (p != NULL){
        array[i++] = p;
        p = strtok(NULL, " ");
    }
    return 0;
}

您可以再次执行此操作以将其进一步拆分.为了解释什么 strtok ,我将用以下代码进行解释:

You can do this again to split it up even further. To explain what strtok does I shall explain with this code :

strtok(word,"); . word 是将要修改的字符串的内容," 是该字符串的定界符.

strtok(word, " ");. word is the content of the string that will be modified and " " with be the delimiter for the string.

这篇关于如何设置一个C函数,将用户输入分为多个部分,还可以将这些较小的部分也分成几个部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆