如何在不使用fgets()的情况下扫描句子中的换行符?

huangapple go评论50阅读模式
英文:

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 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.

huangapple
  • 本文由 发表于 2023年2月10日 12:29:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75406954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定