c - 如何使用 scanf 从下一行输入数据中获取输入?

标签 c string char scanf

我有 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/

相关文章:

c - 是什么导致字符串连接中的段错误?

c++ - 为什么1个元素的数组允许2k个元素?

c - 字符串C中的奇怪字符

c - gcc - 文件无法识别 : File format not recognized

c - MIPS/C 中的钻石排序

c - MinGW/Eclipse C 构建问题 : cannot find dll

c - 如何在 C 中剪切字符串?

objective-c - Objective C 中的 "->"是什么?

Python:是否有快捷方式来查找哪个子字符串(来自一组子字符串)在字符串中排在第一位?

c++ - 使用 const char 出错