我正在上我的第一门编码课,并且试图弄清楚如何制作一个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!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句