我有一个关于gets函数的问题。
我目前正在编写2矩阵加法的程序,我对gets函数的行为感到困惑。从我从教程的描述中了解到的有关c中的gets()函数的内容来看,有人说“ 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
我不确定会发生什么,对于矩阵A,第一行输入被跳过,但是对于矩阵B,第一行输入没有被跳过。
我目前正在elemtary luna上使用gedit编写代码,并使用gcc对其进行编译。基本luna在虚拟机上运行。
感谢所有阅读我的问题的人,如果信息不足,请让我知道,希望有人可以帮助我,非常感谢!:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句