简体   繁体   中英

What to add to this Hello World code in C?

I am very new to programming with C and I can't find a way to add to this program in order to spell "Hello, World!" without deleting any lines of code here.

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

void modify_1(char *c);
void modify_2(char *c);

int main()
{
    char str1[10];
    char str2[15];
    printf("%s, %s!\n", str1, str2);
}

void modify_1(char *c)
{
    char *a_string = "hello";
}

void modify_2(char *c)
{
    char *a_string = "world";
}

Consider the following code (see here in onlineGDB):

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

void modify_1(char *c);
void modify_2(char *c);

int main(void)
{
    char str1[10];
    char str2[15];

    modify_1(str1);
    modify_2(str2);
    printf("%s, %s!\n", str1, str2);
}

void modify_1(char *c)
{
    strcpy(c, "hello");
}

void modify_2(char *c)
{
    strcpy(c, "world");
}

There are a few changes:

  1. You actually call modify_1 and modify_2 (otherwise, why would they affect anything?)
  2. Within the functions, you use strcpy to copy the content of the literal to the address.

I can't find a way to add to this program in order to spell "Hello, World!" without deleting any lines of code here.

Given that you cannot delete any lines, you need only add 2-lines of code to each of your modify_1 and modify_2 functions to (1) copy the string-literals to your array, and then (2) change the first characters from lowercase to uppercase, and then just call modify_1 and modify_2 before you print. For example:

void modify_1 (char *c)
{
    char *a_string = "hello";
    strcpy (c, a_string);         /* copy a_string to your array */
    c[0] = c[0] + 'A' - 'a';      /* change 1st character to uppercase */
}

void modify_2 (char *c)
{
    char *a_string = "world";
    strcpy (c, a_string);         /* same thing */
    c[0] = c[0] + 'A' - 'a';
}

After making the changes, you simply call the functions before your print statement in main() , eg

int main()
{
    char str1[10];
    char str2[15];

    modify_1 (str1);
    modify_2 (str2);

    printf("%s, %s!\n", str1, str2);
}

Example Use/Output

$ ./bin/modify_12
Hello, World!

See ASCII Table and Description to understand how the conversion from lowercase to uppercase takes place.

This is probably not what is intended by the person that gave you the assignment but the simplest solution is to add two lines in main and leave the rest unchanged (and unused:-)

int main()
{
    char str1[10];
    char str2[15];
    strcpy(str1, "Hello");  // Add this line
    strcpy(str2, "World");  // Add this line
    printf("%s, %s!\n", str1, str2);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM