扩展的Hello World计划

时间:2014-08-27 00:33:49

标签: c cygwin

我正在参加我的第一个编码课,我正在试图弄清楚如何制作一个Hello,World!程序询问我的名字,然后回复它。我们的导师给了我们一句话:

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

int main(int argc,char **argv)
{
    int x;

    printf("hello, world!\n");
    printf("give me a number! ");
    scanf(" %d",&x);
    printf("%d is my favorite number!!\n",x + 1);
    return 0;
}

这是一个工作的hello world程序,在编译时,但我们必须让它也要求我们的名字,这是我无法弄清楚的。

这是他的暗示:

#include <string.h>

char s[512];                        //allocate an array to hold a string
printf("type in some stuff: ");
fgets(s,sizeof(s),stdin);           //read in a string of characters
s[strlen(s) - 1] = '\0';            //remove the newline character
printf ("you typed %s!\n", s);
//NOTE: this code fails if string is larger than 511 characters

但我知道几乎没有关于编码的信息,对我来说并不是很有帮助。

当提示“hello”

时,最终结果应该是这样的
What is your name? Fred
hello Fred
give me a number! 10
100 is my favorite number!!

编辑:我试过建模“你叫什么名字?”在“给我一个数字”之后,但它没有奏效。

编辑2:此代码

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

int main(int argc,char **argv)
{
    char s[512];

    printf("What is your name? ");
    fgets(s,sizeof(s), stdin);
    s[strlen(s) - 1] =  '\0];
    printf ("Hello %s!\n", s);
    return 0;
}

返回一个显然不适合帖子的错误。

1 个答案:

答案 0 :(得分:0)

为什么不能改变提示?

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

// This is the main function. Anything inside the { } will be run by the computer
int main(int argc,char **argv)
{
    char s[512]; // This will be the variable that holds the user's name (or whatever they type in)                     
    printf("What is your name? "); // Ask the user for their name
    fgets(s,sizeof(s), stdin); // Get whatever the user types in and put it in the variable s
    s[strlen(s) - 1] = '\0'; // Remove the newline character from s (what the user typed in)
    printf ("Hello %s!\n", s); // Print out "Hello" followed by whatever the user typed in (their name, which is stored in the variable s)

    // End the main function
    return 0;
}

输出应为

What is your name? (User types in Fred)
Hello Fred!