我有 5 行输入,我只关心使用其中两行(它们位于文本文件中):
1 -- input function one
L 123.0 21.0
2 -- input function 2
2.0 3.0
3.0 2.0
我想从第一行开始使用 1,然后跳到第 2 行。
使用完第 2 行后,我想读取第 3 行中的数字 2。
我想再次跳到该行末尾并使用第四行和第五行。
我只能使用 getchar()、scanf、if 和 while 来执行此操作。 这是我的代码的一部分,我只是想让它工作。
int
main(int argc, char *argv[]) {
char ch;
int j;
if(scanf("%d", &j) == 1){
printf("Got %d lines\n", j);
}
scanf("%c", &ch);
printf("%c", ch);
return 0;
}
如果我放
scanf("%d -- input function one\n", &j)
然后我就到达了我想要的位置,但仅适用于“--'stuff'”是 scanf 中 %d 之后的确切短语的情况。
我可以做些什么来跳到行尾吗?获取输出:
有 1 行
L
最佳答案
这是我的建议。
// Read 1 from the first line.
if(scanf("%d", &j) == 1){
printf("Got %d lines\n", j);
}
// Read the rest of the line but don't
// save it. This is the end of the first line
scanf("%*[^\n]s");
// Read the next line but don't save it.
// This is the end of the second line.
scanf("%*[^\n]s");
// Now read the 2 from the third line.
if(scanf("%d", &j) == 1){
printf("Got %d lines\n", j);
}
// Read the rest of the line but don't
// save it. This is the end of line 3
scanf("%*[^\n]s");
// Now the fourth line can be read.
更新
线条
scanf("%*[^\n]s");
应该是
scanf("%*[^\n]s\n");
以便同时使用'\n'
。
关于c - 如何使用 scanf 从下一行输入数据中获取输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23556928/