2012-01-22 82 views
1

我必須使用fputs來打印某些內容,而fputs需要使用「const char * str」來打印出來。 我有3個字符串打印(我不關心它是字符串還是字符[])作爲str。 我不知道正確的做法。我使用了3個字符串,我將它們添加到一個,但不工作。我也嘗試將字符串轉換爲字符,但沒有任何工作! 有什麼建議嗎?Const char * str問題

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

我希望我的字符常量*海峽= user_info-> pw_name + '@' + uts.nodename

回答

2

一種可能的解決方案:

/* 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); 

編輯:

如果C++您可以使用std::string

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

// s.c_str(); this will return const char* to the string. 
+0

我得到無效*‘到‘字符*’ – BlackM

+0

雖然代碼是正確的,[使用strcat'的'是危險的(HTTP「從無效的轉換’: //stackoverflow.com/questions/936468/why-does-msvc-consider-stdstrcat-to-be-unsafe-c),應該避免(對於'strcpy'也一樣)。 – DarkDust

+1

猜測這是一個C++源代碼,所以將'malloc()'的返回值轉換爲'char *'。如果您使用的是C++,那麼建議您使用'std :: string'而不是自己管理內存。 – hmjd

3

您需要爲此創建一個新字符串。我不知道爲什麼你需要fputs限制,但我認爲即使你不能/不想使用fprintf,你仍然有snprintf可用。然後你會做這樣的:

char *new_str; 
int new_length; 

// Determine how much space we'll need. 
new_length = snprintf(NULL, "%[email protected]%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, "%[email protected]%s", user_info->pw_name, uts.nodename); 
+0

+1安全.. – hmjd