C 矩阵代码的方向正确吗?
我的老师说开始的方法是使用书中的 getline() 函数,然后从行中获取数字,然后将这些数字制成矩阵形式,我不明白为什么要使用 getline?
//最终这段代码应该接受一个方阵并且从2x2到6x6 //计划是让它读取一行,然后从该行获取数字, //然后以矩阵形式打印出数字。这就是今天的目标。 //稍后我将尝试让实际的矩阵部分工作
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//error list for error checking will need later I guess (from my notes)
#define ENDOFFILE -1
#define TOOMANYNUMS -2
#define LIMIT 256
//functions declared
int get_line(char line[], int);
//main
main(){
char line[255];
int num[6];
printf("Please input numbers %c: ", line);
get_line(line,LIMIT);
}
//functions
int get_line(char s[],int lim){
int c, i;
for (i=0;i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if(c=='\n'){
s[i]=c;
++i;
}
s[i]='\0';
return i;
}
My instructor said the way to start this is to use the getline() function from out book, then get the numbers from the line, then have those numbers in matrix form, I do not understand why I would use getline?
//eventually this code should take in a square matrix and from 2x2 to 6x6
//the plan is to get it to read in a line, then get the numbers from the line,
//then print out the numbers in a matrix form. That is the goal for today.
//later I will try to get the actual matrix part working
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//error list for error checking will need later I guess (from my notes)
#define ENDOFFILE -1
#define TOOMANYNUMS -2
#define LIMIT 256
//functions declared
int get_line(char line[], int);
//main
main(){
char line[255];
int num[6];
printf("Please input numbers %c: ", line);
get_line(line,LIMIT);
}
//functions
int get_line(char s[],int lim){
int c, i;
for (i=0;i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if(c=='\n'){
s[i]=c;
++i;
}
s[i]='\0';
return i;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
getline(char[], int) 函数使用 getchar() 从控制台读取字符并将它们存储在数组 s[] 中。数组 s[] 与 main() 函数中的 line[] 数组指向同一内存。
The getline(char[], int) function reads characters from the console with getchar() and stores them in the array s[]. The array s[] points at the same memory as the line[] array in the main() function.
getline
不仅返回行的长度,还将第一行复制到s
参数中。因此,在调用getline(line,LIMIT)
(顺便说一句,它不会将返回值存储在任何地方)之后,line
变量将包含第一行。编辑:我还应该指出,在 getline 调用上方的
printf
正在引用line
变量,该变量未初始化,是一个 char 数组,而不是单个变量字符getline
is not just returning the lenth of the line, it's also copying the first line into thes
parameter. So after your call ofgetline(line,LIMIT)
(which doesn't btw, store the return value anywhere), theline
variable will contain the first line.Edit: I should also point out that your
printf
just above the call to getline is referencing theline
variable, which is uninitialized and a char array, not a single character