【问题标题】:C Program Array more than 1 word [closed]C程序数组超过1个字[关闭]
【发布时间】:2016-08-19 17:32:23
【问题描述】:

这个问题来自 HackerRank,我尝试用 %[^\n]s 表示一个长词。但是,输出继续产生.0

如何将 %[^\n]s 替换为其他字符串以接收输入?

这是输入:

12
4.0
is the best place to learn and practice coding!

这是我的输出:

16
8.0
HackerRank  .0

这是预期的输出:

16
8.0
HackerRank is the best place to learn and practice coding!

这是我的完整代码,如您所见,它无法识别 %[^\n]s。如何解决这个问题呢?谢谢你。

完整代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main() {
    int i = 4;
    double d = 4.0;
    char s[] = "HackerRank ";

    // Declare second niteger, double, and String variables.
    int value1, sum1, value2;
    double e = 2.0, sum2;
    char t[30];

    // Read and save an integer, double, and String to your variables.
    scanf(" %d", &value1);
    scanf("%d", &value2);
    scanf("%[^\n]s", t); //** POINT OF INTEREST **

    // Print the sum of both integer variables on a new line.
    sum1 = value1 + i;
    printf("%d\n", sum1);

    // Print the sum of the double variables on a new line.
    sum2 = d * e;
    printf("%.1lf\n", sum2);

    // Concatenate and print the String variables on a new line
    // The 's' variable above should be printed first.
    printf("%s %s", s, t);

    return 0;
}

【问题讨论】:

  • 请澄清您的问题。检查How to Ask
  • 如何将 %[^\n]s 替换为其他字符串以接收输入?
  • 流中可能有一个换行符,从您读取的最后一个数字开始。这会导致%[^\n] 失败,因为在下一个换行符之前没有要读取的字符。另外,%[] 之后不需要s
  • 我没有投反对票,但这里有一个提示。发布代码时,只需将其粘贴到您的问题中,缩进 4 个或更多空格。该网站会将其视为代码,并且每个人都可以更轻松地阅读。
  • 使用scanf 盲目地将任意长度的用户输入读取到固定大小的缓冲区中只是在乞求缓冲区溢出。 fgets 可能就是你要找的:stackoverflow.com/questions/1252132/…

标签: c arrays


【解决方案1】:

考虑到您的输入输出示例,我将您的代码修改如下:

char t[256]; // the string "is the best place to learn and practice coding!" MUST FIT!!!
...
scanf("%d", &value1);
scanf("%lf", &d); // NOT %d, %lf !!! &d or &e - I don't know - depends on you
scanf("\n%[^\n]", &t);
...
printf("%s%s", s, t); // you don't need a space, since your "s" already contains it.

对我来说很好。

更新: 现在它实际上工作正常。

【讨论】:

  • @BLUEPIXY 怎么了?
  • @BLUEPIXY 明白了。现在看来是对的。
  • @BLUEPIXY 你是对的,谢谢。
【解决方案2】:

scanf() 未能读取字符串的原因很可能是在您扫描最后一个数字后,流中仍有一个换行符未被读取。 "%[^\n]" 尝试读取一个字符串,其中包含除换行符以外的任何内容,并在到达无效字符时停止;由于下一个字符是换行符,因此没有要读取的有效字符并且无法分配该字段。修复它所需要做的就是在扫描字符串之前读取换行符。

另外,%[ 说明符最后不需要s——它是与%s 不同的转换说明符,而不是它的修饰符。

最后,建议您指定%[%s 的宽度,这样长输入字符串就不会超出您将字符串读入的缓冲区。宽度应该是 null 之前要读取的最大字符数,因此比缓冲区大小小一。

使用scanf(" %29[^\n]",t) 将在扫描字符串之前读取空格(包括该换行符),然后扫描包含最多 29 个非换行符的字符串(对于 30 字符的缓冲区)。

【讨论】:

    猜你喜欢
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 2021-09-27
    相关资源
    最近更新 更多