【问题标题】:Is it possible to use std::string in a program as part of if else statement [closed]是否可以在程序中使用 std::string 作为 if else 语句的一部分 [关闭]
【发布时间】:2013-12-14 10:48:24
【问题描述】:
 if(condition)
    {
      std::string interface = string1;
    }
    else
    {
      std::string interface = string2;
    }

谁能告诉我这在 C 程序中是否可行。

【问题讨论】:

  • std::string 是标准 C++ 库的一部分,因此不能在 C 程序中使用,而只能在 C++ 程序中使用。但是,如果您使用 C++ 编程,那么可以这样做。
  • 在 C++ 中是可能的。但是你想解决什么问题?

标签: c++ c stdstring


【解决方案1】:

在 C++ 中是可能的,但在您的代码示例中,interface 仅存在于if-else 的每个块的有限范围内。如果要根据某个条件实例化一个字符串,可以使用条件运算符:

std::string interface = condition ? string1 : string2;

【讨论】:

    【解决方案2】:

    首先,std::string 只能在 C++ 程序中使用。

    其次,如果您像以前那样声明,那么您有两个变量,其范围分别包含在ifthen 部分和ifelse 部分:

    if(condition)
        {
          // variable scope start
          std::string interface = string1;
          // variable scope end. beyond this point, the variable interface no longer exist.
        }
        else
        {
          // variable scope start (the old variable interface no longer exists. this is a new variable
          std::string interface = string2;
          // variable scope end.
        }
    // at this point none of the variable exist anymore.
    

    你应该做的是:

    std::string interface;
    if (condition) {
      interface = string1;
    } else {
      interface = string2;
    }
    

    或者,正如@juanchopanza 所说:

    std::string 接口 = 条件? string1 : string2;

    【讨论】:

      【解决方案3】:

      正如这里所说,在 C++ 中是可能的,但在 C 中是不可能的,因为 C 没有 std::string 类型。此外,您的示例没有太大意义,因为每个变量接口仅在相应的复合语句中有效,而在 if-else 语句之外将无法访问。

      在 C 语言中,您应该使用字符数组和标准函数 strcpy。例如

      char interface[20];
      
       if(condition)
          {
            strcpy( interface, string1 );
          }
          else
          {
            strcpy( interface, string2 );
          }
      

      前提是变量接口足够大,可以容纳字符数组string1或string2

      【讨论】:

        猜你喜欢
        • 2015-06-09
        • 1970-01-01
        • 2021-10-22
        • 1970-01-01
        • 1970-01-01
        • 2017-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多