1

I have to use fputs to print something and fputs take "const char *str" to print out. I have 3 strings to print(I don't care if it's strings or char[]) as str. I dont know the right way to do it. I used 3 string and I added them to one but is not working. I also tried to convert string to char but nothing is working! Any recommendations?

struct passwd* user_info = getpwuid(getuid()); 
struct utsname uts;
 uname(&uts);

I want my char const *str = user_info->pw_name + '@' + uts.nodename

hmjd
  • 120,187
  • 20
  • 207
  • 252
BlackM
  • 3,927
  • 8
  • 39
  • 69

2 Answers2

3

You need to create a new string for that. I have no idea why you need the fputs restriction, but I assume that even if you can't/don't want to use fprintf, you still have snprintf available. You'd then do it like this:

char *new_str;
int new_length;

// Determine how much space we'll need.
new_length = snprintf(NULL, "%s@%s", user_info->pw_name, uts.nodename);
if (new_length < 0) {
    // Handle error here.
}
// Need to allocate one more character for the NULL termination.
new_str = malloc(new_length + 1);
// Write new string.
snprintf(new_str, "%s@%s", user_info->pw_name, uts.nodename);
DarkDust
  • 90,870
  • 19
  • 190
  • 224
2

A possible solution:

/* 1 for '@' and 1 for terminating NULL */
int size = strlen(user_info->pw_name) + strlen(uts.nodename) + 2;
char* s = malloc(size);

strcpy(s, user_info->pw_name);
strcat(s, "@");
strcat(s, uts.nodename);


/* Free when done. */
free(s);

EDIT:

If C++ you can use std::string:

std::string s(user_info->pw_name);
s += "@";
s += uts.nodename;

// s.c_str(); this will return const char* to the string.
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • i get 'invalid conversion from ‘void*’ to ‘char*’ – BlackM Jan 22 '12 at 15:58
  • While the code is correct, the [use of `strcat` is dangerous](http://stackoverflow.com/questions/936468/why-does-msvc-consider-stdstrcat-to-be-unsafe-c) and should be avoided (same for `strcpy`). – DarkDust Jan 22 '12 at 15:59
  • 1
    Guessing this is a C++ source so cast return value from `malloc()` to `char*`. If you are using C++ then recommend using `std::string` instead of managing memory yourself. – hmjd Jan 22 '12 at 16:00
  • @user776720 Where ? Perhaps you're compiling the code as C++, instead of C. – nos Jan 22 '12 at 16:01
  • fix it with char* s = (char*)malloc(size); – BlackM Jan 22 '12 at 16:07
  • @user776720: Which of two solutions are you using? The C or C++ one? – DarkDust Jan 22 '12 at 16:14
  • Take heed of @DarkDust comment regarding the unsafety of `strcat()`. – hmjd Jan 22 '12 at 16:15