C字符串未运行

问题描述 投票:-3回答:2

因为我是一名新手程序员和编码器所以,我在Hackerrank中进行了30天的编码挑战,但是当我在C中运行简单的字符串存储问题时,它显示没有错误代码是

#include <stdio.h>
int main() {
    int i = 4;
    double d = 4.0;
    char s[] = "HackerRank ";
    // Declare second integer, double, and String variables.

    // Read and save an integer, double, and String to your variables.

    // Print the sum of both integer variables on a new line.

    // Print the sum of the double variables on a new line.

    // Concatenate and print the String variables on a new line
    // The 's' variable above should be printed first.
int ie;double de;char re[1000];
printf("Enter the int,double,string value :");
scanf("%d %lf %s",&ie,&de,re);
printf("\n%d\n%lf\n%s",(ie+i),(de+d),s);
printf("%s\n",re);
 return 0;
}

输入:

12 
4.0
is the best place to learn

预期产量:

16
8.0
HackerRank is the best place to learn

实际产量:

Enter the int,double,string value :
16
8.000000
HackerRank is
c scanf
2个回答
1
投票

要点是:

  • 你不应该打印像Enter the int,double,string value :那样没有预料到的东西,否则法官系统会将它们视为垃圾并视为错误答案。
  • %s将停止在空白处阅读。 fgets可用于读取一行。 %d%lf不会使用换行符,因此需要注意。
  • 根据问题设置,可以接受或不接受浮点数的打印格式的差异。这在下面的示例中没有修复。

试试这个:

#include <stdio.h>
#include <string.h> /* for using strchr() */
int main() {
    int i = 4;
    double d = 4.0;
    char s[] = "HackerRank ";

    int ie;double de;char re[1000];
    char *lf;
    fgets(re, sizeof(re), stdin); sscanf(re, "%d", &ie);
    fgets(re, sizeof(re), stdin); sscanf(re, "%lf", &de);
    fgets(re, sizeof(re), stdin);
    if ((lf = strchr(re, '\n')) != NULL) *lf = '\0'; /* remove newline character if it exists */
    printf("%d\n%f\n%s",(ie+i),(de+d),s);
    printf("%s\n",re);
    return 0;
}

0
投票

这可能有所帮助:

#include <stdio.h>

int main() {
    int i = 4;
    double d = 4.0;
    char s[] = "HackerRank ";
    int x;
    double y;
    char z[50];
    scanf(" %d %lf\n%[^\n]", &x, &y, z);
    printf("%d\n", x+i);
    printf("%.1lf\n", y+d);
    printf("%s", s);
    printf("%s", z);
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.