英文:
How can I scan newline in a sentence without fgets();
问题
首先,将一个字符 ch 作为输入。
然后将字符串 s 作为输入。
最后,将句子 sen 作为输入。
这是由 hackerrank 提供的任务,听说它不接受 fgets()。
int main(){
char ch, s[50], sen[100];
scanf("%c%s%[^\n]%s", &ch, s, sen);
printf("%c\n%s%s", ch, s, sen);
return 0;
}
这是我的代码,扫描函数中有一个问题 - "%[^n]%s" 这是错误的,应该是 "%[^\n]%s",但不知何故它仍然有效,如果我更正它,就会出现错误。
出了什么问题?
英文:
First, take a character, ch as input.
Then take the string, s as input.
Lastly, take the sentence sen as input.
This was the task provided by hackerrank and ive heard that it does not accept fgets()
int main(){
char ch, s[50], sen[100];
scanf("%c%s%[^n]%s", &ch, &s, &sen);
printf("%c\n%s%s", ch, s, sen);
return 0;
}
this is my code and there's a problem in the scan function - "%[^n]%s" this is wrong and it is supposed to be "%[^\n]%s" but somehow it works and if i correct it, it gives me an error.
What went wrong?
答案1
得分: 1
scanf("%c%s%[^n]%s", &ch, s, sen);
is bad.
-
Code not compiled with a well-enabled compiler that would complain about mis-matched types. "%s" expects a "char *". s is not a "char *".
-
Code has 4 specifiers yet only 3 following arguments.
-
Return value not checked.
-
Missing widths risk buffer overflow.
-
Code does not limit to 1 line as "%s" consumes any number of leading white-space including multiple '\n'.
To robustly read a single line of user input via scanf() is non-trivial. Most attempts have many holes - even if it works for some test cases.
英文:
> What went wrong?
scanf("%c%s%[^n]%s", &ch, &s, &sen);
is bad.
-
Code not compiled with a well enabled compiler that would complain about mis-matched types.
"%s"
expect achar *
.&s
is not achar *
. -
Code has 4 specifiers yet only 3 following arguments.
-
Return value not checked.
-
Missing widths risk buffer overflow.
-
Code does not limit to 1 line as
"%s"
consumes any number of leading white-space including multiple'\n'
.
To robustly read a single line of user input via scanf()
is non-trivial. Most attempts have many holes - even if it works for some test cases.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论