gpt4 book ai didi

c - 扩展 Hello World 程序

转载 作者:行者123 更新时间:2023-11-30 20:39:53 25 4
gpt4 key购买 nike

我正在参加我的第一堂编程课,我正在尝试弄清楚如何制作一个 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;
}

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

最佳答案

为什么不能直接更改提示?

#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!

关于c - 扩展 Hello World 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25517185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com