如何扫描多个值并添加到数组? [英] How to scanf multiple values and add to an array?

查看:124
本文介绍了如何扫描多个值并添加到数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个NxN大小的矩阵(N是2到10之间的数字),我们可以放下棋子。您只能在一个字段中放置一个。程序要求桌子的大小,然后要求象棋的位置。

1.件:B2

2.件:C5

3.件:D2

...


在最后一块之后,用户可以通过键入 x退出循环。

There is an NxN sized Matrix (N is a number between 2-10) where we can put down chess pieces. You can put only one piece of one field. The program asks for the size of the table then asks for the chess pieces position like this.
1. piece: B2
2. piece: C5
3. piece: D2
...
After the last piece the user can exit from the loop by typing an 'x'.

我的问题是我必须将所有这些数据放入一个这样的数组中:

My problem is that I have to put all this data into one array like this:

char position[100] = {B2C5D2}

这是代码我尝试使用的函数:

This is the code to the function I tried to use:

char inputPosition(char position[]) {
    int i = 0;
    do {
        printf("%d. piece: ", i+1);
        scanf("%s", &position[i]);
        i++;
    }while(position[i-1]!='x');
    return position;
}

输出看起来像这样:(对于B2C5D2)

The output looks like this: (for B2C5D2)

BCDx

I'我不确定我应该使用scanf并且程序不应该将值x作为参数,但是我不知道该怎么做。

I'm not sure I should use scanf and the program shouldn't get the value x as a parameter but I don't know what to do.

编辑:在我的示例中,职位是否有效并不重要。我还编辑了char位置的最大输入。 (我必须使用的最大变量约为10)我的真正问题是我无法将每个位置[i]放入一个没有空格的数组中。

It's doesn't matter if the position is valid or not in my example. Also I edited the max input of the char positions. (The max variables I have to use is around 10) My real problem is that I can't put every position[i] into one array without spaces.

推荐答案

您需要偏移数组中的位置,以允许每个条目2个字符,因此请使用 & position [2 * i] 作为 scanf()的参数。

You need to offset the position in the array to allow for 2 characters per entry, so use &position[2*i] as the argument to scanf().

最好告诉您的代码数组的大小,并确保不会溢出该数组(通过索引结尾或通过接受总数超出限制的字符)。

It's a good idea to tell your code how big the array is, and to ensure that you don't overflow that array (either by indexing off the end or by accepting more characters in total than will fit).

一种可能的解决方案是:

One possible solution is:

#include <stdio.h>

static void inputPosition(int pos_size, char position[pos_size])
{
    for (int i = 0; i < pos_size / 2; i++)
    {
        printf("%d. piece: ", i + 1);
        scanf("%2s", &position[2 * i]);
        if (position[2 * i] == 'x')
        {
            position[2 * i] = '\0';
            break;
        }
    }
}

int main(void)
{
    char position[21];

    inputPosition(sizeof(position), position);
    printf("Position: [%s]\n", position);
    return 0;
}

样本运行收益:

1. piece: B2
2. piece: C5
3. piece: D2
4. piece: A1
5. piece: E3
6. piece: F8
7. piece: H8
8. piece: A3
9. piece: D4
10. piece: E2
Position: [B2C5D2A1E3F8H8A3D4E2]

另一个具有提前退出功能的示例是:

Another sample run with early exit is:

1. piece: B2
2. piece: C5
3. piece: D2
4. piece: x
Position: [B2C5D2]

这篇关于如何扫描多个值并添加到数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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