如何计算在℃的矩阵的行元素的量 [英] How to count amount of elements in a row of a matrix in C

查看:144
本文介绍了如何计算在℃的矩阵的行元素的量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用一个整数数组,我还想先问行和列的数量的用户(可以称它们为x和y),他希望阵列(我知道如何做到这一步)英寸它是尽管这很重要,同时用户输入将存储在基质中的值,即一行将从输入的一行,并从输入的第二行等等第二行读取。因此,输入= 1行一行。

Using an integer array, Id like to first ask the user for the amount of rows and columns (lets call them x and y) he wants in the array (i know how to do this step). It is important though that while the user enters the values that will be stored in the matrix, that one row will be read in from one line of input, and the second row from the second line of input and so on. So one line of input=1 row.

所以,如果他定义的列X数量,他应该在第一行一行输入x号,所有。如何检查是否不x数字确实已经上线进入?如果少跌多输入,我会打印错误消息。有某种命令,检查1行的大小,以便它可以检查它针对用户已经定义在x

So if he has defined x amount of columns, he should enter x numbers for the first row, all on one line. How can i check whether or not x numbers have indeed been entered on the line? If less or more are entered i will print an error message. Is there some kind of command that checks the size of 1 row, so that it can check it against the x that the user has defined?

在code到目前为止我已经写涉及到简单的步骤,但我对如何实现这一检查,以确认用户输入因为他最初定义的投入同样数额不大的想法。

The code I have written thus far involves the simple steps, but I have little ideas about how to implement this check, to confirm that the user is entering the same amount of inputs as he has defined originally.

非常感谢!

推荐答案

既然你想在一次读取一行,你应该使用与fgets 这正是这么做的。然后你可以使用 strtok的分离用空格/制表符线并尝试每个值转换为int。如果您运行的数字之前该行被填满,或者还有更多的数字行充满后,那么你可以提醒的用户。

Since you want to read one line at a time, you should use fgets which does exactly that. Then you can use strtok to separate the line by spaces/tabs and attempt to convert each value to an int. If you run out of numbers before the row is filled, or still have more numbers after the row is filled, then you can alert the user of that.

下面是一个简单的例子:

Here's a quick example:

void read_array(int **array, int rows, int cols)
{
    char line[100];
    int i,count;
    char *p;

    for (i=0;i<rows;i++) {
        printf("enter row %d: "), i-1);
        fgets(line, sizeof(line), stdin);
        count = 0;
        p = strtok(line, " \t");
        while (p && (count < cols)) {
            matrix[i][count++] = atoi(p);
            p = strtok(NULL, " \t");
        }
        if (count < cols) {
            printf("too few values\n");
            i--;
            continue;
        } else if (p) {
            printf("too many values\n");
            i--;
            continue;
        }
    }
}

这篇关于如何计算在℃的矩阵的行元素的量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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