【问题标题】:How convert cin to const char*如何将 cin 转换为 const char*
【发布时间】:2011-05-23 19:22:09
【问题描述】:

在我的程序中,我通过 iostream 获得输入:

char input[29];
cin >> input;

我需要使用这个输入作为这个类的一个参数,这个参数作为它的构造函数

class::class(const char* value) {
  /* etc */ }

知道如何转换吗?

谢谢

【问题讨论】:

    标签: c++ pointers constructor char


    【解决方案1】:

    您应该能够将input 作为参数传递给您的构造函数。 char[] 将衰减为 char *,与 const char * 兼容。

    但是:流式传输到固定长度的缓冲区是一个非常糟糕的主意(如果有人提供的输入长度超过 28 个字符怎么办?)。请改用std::string(如@George 的回答)。

    【讨论】:

      【解决方案2】:
      string tmp;
      cin >> tmp;
      foo(tmp.c_str());
      

      【讨论】:

      • String => string ... 你还应该解释为什么这是一个比 OP 更好的代码。
      【解决方案3】:

      >> 操作符无法知道它只能读取 29 个字节。
      所以你必须明确指定它:

      char input[29] = { 0 }; // note sets all characters to '\0' thus the read will be '\0' terminated.
      cin.read(input, 28);    // leave 1 byte for '\0'
      

      您也可以使用标准字符串。

      std::string word;
      cin >> word;  // reads one space seporated word.
      
      Class objet(word.c_str()); // Or alternatively make you class work with strings.
                                 // Which would be the correct and better choice.
      

      如果你需要阅读整行而不是一个单词

      std::string line;
      std::getline(std::cin, line);
      
      Class objet(line.c_str()); // Or alternatively make you class work with strings.
                                 // Which would be the correct and better choice.
      

      请注意,在上述所有内容中,您应该在读取后真正检查流的状态,以确保读取正常。

      std::string word;
      if (cin >> word)   // using the if automatically checks the state. (see other questions).
      {
          Class objet(word);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-25
        • 1970-01-01
        • 2015-04-02
        • 1970-01-01
        • 2013-01-26
        • 2019-09-10
        相关资源
        最近更新 更多