gpt4 book ai didi

c - 扫描多行直到到达特定字符

转载 作者:太空宇宙 更新时间:2023-11-04 07:43:51 24 4
gpt4 key购买 nike

我有如下输入:

Someting sth
example
5 15
3

我想按行scanf 输入以获取该行的全部内容。但是当到达第一个数字时(前面可以有空格/制表符)我想将它扫描为 int。

这就是我的想法,但它没有按预期工作 - 光标仍然没有停在数字字符处。

char person_name[1000];
int n;

while (scanf("%[^\n/D]%*c", person_name) > 0) {
if (checkIfContainsNumber(person_name) == 0) {
appendToLinkedList(&head_ref, person_name);
} else {
break;
}
}

while (scanf("%d", &n) > 0) {
printf("%d ", n);
}

最佳答案

据我了解这个问题,每一行都可以被认为是名称序列或整数序列。
所以我会尝试逐行读取文件并分析每个提取的行作为一个或另一个序列(空格被隐式消耗)。
这里的技巧是使用 "%n" 进一步分析同一行。

#include <stdio.h>

int
main(void)
{
FILE *input=fopen("input.txt", "r");
if(!input)
{
return 1;
}
char line[1024];
while(fgets(line, sizeof(line), input))
{
int pos=0;
int value, count;
char name[256];
if(sscanf(line+pos, "%d%n", &value, &count)==1)
{
pos+=count;
printf("a line with values: <%d>", value);
while(sscanf(line+pos, "%d%n", &value, &count)==1)
{
pos+=count;
printf(" <%d>", value);
}
printf("\n");
}
else if(sscanf(line+pos, "%255s%n", name, &count)==1)
{
pos+=count;
printf("a line with names: <%s>", name);
while(sscanf(line+pos, "%255s%n", name, &count)==1)
{
pos+=count;
printf(" <%s>", name);
}
printf("\n");
}
}
fclose(input);
return 0;
}

关于c - 扫描多行直到到达特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58448712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com