如何使用scanf从下一行输入数据获取输入?
我有5行输入,我只关心使用其中两行(它们位于文本文件中): 我想从第一行开始使用1,然后跳到第2行 使用第2行后,我想读取第3行中的数字2 我想再次跳到这一行的末尾,使用第四行和第五行 我只能使用getchar()、scanf、if和while来执行此操作。 这是我代码的一部分,我只是想让它工作如何使用scanf从下一行输入数据获取输入?,c,string,char,scanf,C,String,Char,Scanf,我有5行输入,我只关心使用其中两行(它们位于文本文件中): 我想从第一行开始使用1,然后跳到第2行 使用第2行后,我想读取第3行中的数字2 我想再次跳到这一行的末尾,使用第四行和第五行 我只能使用getchar()、scanf、if和while来执行此操作。 这是我代码的一部分,我只是想让它工作 int main(int argc, char *argv[]) { char ch; int j; if(scanf("%d", &j) == 1){
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行
这是我的建议
// 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”
。我不完全确定“%*[^\n]s”的作用,但这似乎有效。“*”限定符的含义是:“可选的起始星号表示数据将从流中读取,但会被忽略(即它不会存储在参数所指的位置)。“[^\n]s的含义是”:读取所有非'\n'
的字符,并在'\n'
处停止。
scanf("%*[^\n]s\n");