Ajay Philia
Ajay Philia

Reputation: 69

string input parameter for c program

I wrote a function to replace the blank spaces with tab character. But when I tried to implement it using function. I am quite not understanding how to call this function. I need functions

  1. Which takes string from user as input,
  2. Second function which replaces the blank space with tab character,
  3. Function to print the modified string.

I achieved second one:

void SecondFunction()
{
     char string[] = "I am new to c";
     char *p = string;

     for (; *p; ++p)
     {
         if (*p == ' ')
             *p = '\t';
     }
     printf(string);
}

And when I tried to call this function like:

int main()
{
     SecondFunction("Hi s"); 
}

By changing my function to:

void SecondFunction(char* str)
{
    char string[] = str;
    char *p = string;
    ....
    ...etc
}

I get the following error:

 error: invalid initializer
   char string[] = str;
   ^

Please, can anybody help me to write the 3 functions of my requirement?

Upvotes: 0

Views: 9347

Answers (1)

flogram_dev
flogram_dev

Reputation: 42888

  1. Reading user input

    To read input from the user you can use scanf. You need to pass it the memory address of the variable where you want to store the input:

    char userinput[256]; // make it large enough to hold what the user inputs
    scanf("%s", userinput); // array decays to pointer so no '&' here
    

    The %s means were reading string input. We could also read an int using %d, like this:

    int i;
    scanf("%d", &i); // note the address-of operator '&' to get the address of i
    
  2. Printing variables

    Your SecondFunction is almost correct. To printf a C-string you need to use a syntax similar to when you scanf to a variable:

    printf("%s", string);
    

    Similarly, you could print the int i like this:

    printf("The number is: %d", i);
    
  3. Copying C-strings

    When you tried doing this: char string[] = str, that's not possible. Arrays cannot be assigned or even copy constructed.

    Just in case for the future, when you want to copy a C-string, you need to use strcpy:

    char string[256]; // again, must be large enough to hold the new contents
    strcpy(string, str); // copies from str to string
    

    So in conclusion, your function could look something like this:

    void SecondFunction(char* str)
    {
        char string[256];
        strcpy(string, str);
        char *p = string;
        for (; *p; ++p)
        {
            if (*p == ' ')
                *p = '\t';
        }
        printf("%s", string);
    }
    

    Bonus: Why you can't write to the str parameter directly

    When you write this: SecondFunction("Hi s"), the string "Hi s" gets stored in a read-only memory segment.

    If you then go and try to modify the parameter inside SecondFunction, you get undefined behavior, possibly a segmentation fault.

Upvotes: 4

Related Questions