Home > Enterprise >  Write an argument to a string in C
Write an argument to a string in C

Time:12-15

I am trying to write an argument to a string. What am I doing wrong? How would it be more correct to write the argument from getopt to a string?

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

int main(int argc, char *argv[])
{
    char fsrt[100], sstr[100], tstr[100];
    int rez = 0;
    while ( (rez = getopt(argc, argv, "f:s:l:")) != -1 )
    {
        if (rez == 'f') {
                strcat(fsrt, optarg);
        }
        if (rez == 's') {
                strcat(sstr, optarg);
        }
        if (rez == 'l') {
                strcat(tstr, optarg);
        }
    }


    printf("%s %s %s", fsrt, sstr, tstr);

    return 0;
}

Update: strange symbol in output.

./test -f one -s two -l three
output: https://i.stack.imgur.com/kksVh.png

CodePudding user response:

char fsrt[100] = "", sstr[100]= "", tstr[100]= "";

If you don't initialize the char arrays they randomly point somewhere in memory.

  •  Tags:  
  • c
  • Related