我有一个问题,我想问一下获取功能。
我目前正在编写一个2矩阵加法程序,我对gets函数行为感到困惑。根据我从教程点的描述中读到的关于c中的gets()函数的内容,可以说“获取函数将在成功时返回str,在出错时或在文件结束时没有读取任何字符时返回NULL”。
for (matrix_number = 0; matrix_number < 2; matrix_number++)
{
if (matrix_number == 0) { printf("MATRIX A\n"); }
else { printf("MATRIX B\n"); }
// dim = the dimension of the matrix that the user inputted
// Loop counter is for cycling through the matrix row, if dim is 3 then cycle 3x
// The user will type in the data in a format like this
// Type in the data for row 1 : 1 2 3
// 1 is the value for the first row and first column for the matrix
// 2 is the value for the first row and second column for the matrix and so on
for (loop_counter = 1; loop_counter <= dim; loop_counter++)
{
char row_value[20], space[2] = " ", *value_token;
printf("Type in the data for row %d :",loop_counter);
gets(row_value);
value_token = strtok (row_value,space);
while (value_token!=NULL)
{
insert( atoi(value_token) , matrix_number);
// convert value_token from string to int type
value_token = strtok (NULL,space);
}
}
}
它编译,但是当我运行程序时,我得到了类似的东西
Welcome to the Matrix Addition Calculator Program!
Type in the dimension of the matrix : 3
MATRIX A
Type in the data for row 1 :Type in the data for row 2 :6 5 4
Type in the data for row 3 :3 2 1
MATRIX B
Type in the data for row 1 :1 2 3
Type in the data for row 2 :4 5 6
Type in the data for row 3 :7 8 9
我不确定会发生什么,对于Matrix A,跳过第一行输入,但对于Matrix B,不跳过第一行输入。
我目前正在elemtary luna上使用gedit来编写代码和gcc来编译它。基本的luna正在虚拟机上运行。
感谢所有读过我问题的人,如果信息不够,请告诉我,希望有人能帮助我,非常感谢! :)
答案 0 :(得分:4)