[英]How to scan a string with white spaces in structure members in C?
struct Demo{
char a[50];
char b[50];
int a;
};
Can anyone give the code for this structure Demo where a and b will contains string with different words[white-spaces]. 任何人都可以提供此结构演示的代码,其中a和b将包含具有不同单词的字符串[空白]。
I tried 我试过了
scanf("[^\\n]s",name.a); //where name is the object
fgets(name.a,50,stdin);
Note : we can't use gets
method as well 注意:我们也不能使用
gets
方法
So, If any other method is there, please provide me. 因此,如果有其他方法,请提供给我。
To read a line of user input into char a[50];
将一行用户输入读入
char a[50];
with its potential trailing '\\n'
trimmed: 其潜在的尾随
'\\n'
修剪:
if (fgets(name.a, sizeof name.a, stdin)) {
name.a[strcspn(name.a, "\n")] = '\0'; // trim \n
}
Work is needed to cope with consuming excessive long input lines and using the last element of name.a[]
such as: 需要进行工作以解决占用过多的长输入行并使用
name.a[]
的最后一个元素的问题,例如:
// 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';
}
The scanf("%49[^\\n]%*c", name.a)
approach has trouble in 2 cases: scanf("%49[^\\n]%*c", name.a)
方法在2种情况下存在问题:
1) The input is only "\\n"
, nothing is saved in name.a
and '\\n'
remains in stdin
. 1)输入仅为
"\\n"
, name.a
未保存任何内容,而stdin
仍保留'\\n'
。
2) With input longer than 49 characters (aside from the '\\n'
), the %*c
consumes an extra character, yet the rest of the long input line remains in stdin
. 2)输入超过49个字符(除了
'\\n'
), %*c
会占用一个额外的字符,但长输入行的其余部分仍保留在stdin
。
Both of these issues can be solves with additional code too. 这两个问题也可以使用其他代码来解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.