struct Demo{
char a[50];
char b[50];
int a;
};
谁能给出该结构演示,其中A和B将包含串具有不同的字[空白频段]的代码。如何用C中的结构成员中的空格扫描字符串?
我试图
scanf("[^\n]s",name.a); //where name is the object
fgets(name.a,50,stdin);
注:我们不能使用gets
方法以及
所以,如果有任何其他的方法是那里,请公关欢迎我。
struct Demo{
char a[50];
char b[50];
int a;
};
谁能给出该结构演示,其中A和B将包含串具有不同的字[空白频段]的代码。如何用C中的结构成员中的空格扫描字符串?
我试图
scanf("[^\n]s",name.a); //where name is the object
fgets(name.a,50,stdin);
注:我们不能使用gets
方法以及
所以,如果有任何其他的方法是那里,请公关欢迎我。
读取用户输入的线成char a[50];
其修剪潜在尾随'\n'
:应付消耗过多的长条输入线和使用这样name.a[]
的最后一个元素是需要
if (fgets(name.a, sizeof name.a, stdin)) {
name.a[strcspn(name.a, "\n")] = '\0'; // trim \n
}
工作:
// Alternative
if (scanf("%49[^\n]", name.a) == 1) {
// consume trailing input
int ch;
while ((ch = fgetc(stdin)) != '\n' && ch != EOF) {
;
}
} else { // Handle lines of only \n, end-of-file or input error
name.a[0] = '\0';
}
的scanf("%49[^\n]%*c", name.a)
APPR oach在2种情况下有问题:
1)输入仅为"\n"
,name.a
和'\n'
仍保留在stdin
中。
2)输入长度超过49个字符(除'\n'
之外),%*c
消耗一个额外的字符,但长输入行的其余部分保留在stdin
。
这两个问题都可以通过附加代码解决。
你的输入是怎样的?如果是一行一行地,'fgets()'应该是好的。 –
不应该在'scanf(...)'的某个地方有'%'? – Yunnosch
有没有办法给出这样的好答案,请提供[MCVE](https://stackoverflow.com/help/mcve) –