【问题标题】:Const char * str issueconst char * str 问题
【发布时间】:2012-01-22 15:51:45
【问题描述】:

我必须使用 fputs 来打印一些东西,而 fputs 需要 "const char *str" 来打印出来。 我有 3 个字符串要打印(我不在乎它是字符串还是 char[])作为 str。 我不知道正确的方法。我使用了 3 个字符串,并将它们添加到一个字符串中,但无法正常工作。我也尝试将字符串转换为字符,但没有任何效果! 有什么建议吗?

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

我想要我的 char const *str = user_info->pw_name + '@' + uts.nodename

【问题讨论】:

    标签: c string char


    【解决方案1】:

    您需要为此创建一个新字符串。我不知道你为什么需要fputs 限制,但我认为即使你不能/不想使用fprintf,你仍然有snprintf 可用。然后你会这样做:

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

    【讨论】:

      【解决方案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.
      

      【讨论】:

      • 我得到 '从'void*' 到 'char*' 的无效转换
      • 虽然代码正确,但应避免使用use of strcat is dangerous(strcpy 相同)。
      • 猜测这是一个 C++ 源代码,所以将返回值从 malloc() 转换为 char*。如果您使用的是 C++,那么建议您使用 std::string 而不是自己管理内存。
      • @user776720 在哪里?也许您将代码编译为 C++,而不是 C。
      • 用 char* s = (char*)malloc(size); 修复它
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      • 2018-07-30
      • 1970-01-01
      • 2018-12-20
      相关资源
      最近更新 更多