【问题标题】:How to make a string variable that contains more than one letter?如何制作包含多个字母的字符串变量?
【发布时间】:2018-01-27 16:18:27
【问题描述】:

仅使用 char 可以创建单个字符变量。你会如何用一个词来做一个变量?搜索后我发现了这种方式:

#include <iostream>
int main()
{
char word[] = "computer";
std::cout<< "choose" << word << std::endl;
return 0;
}

这提供了我需要的东西,但我认为这不是正确的方法? 那么这是正确的方法吗:在 char 的变量后放置空括号?

【问题讨论】:

  • 您从什么来源学习 C++? (另外,#include iostream 是一个语法错误。)
  • std::string word = "computer"s; 应该可以正常工作。
  • 声明变量的方法有很多种。您可以使用 char 数组或 char 指针或字符串数​​据类型。这取决于您要查找的内容以及您将如何在代码中使用变量
  • std::string 被管理并拥有大量有用的实用程序。通常,指向字符串文字和 char 数组的常量 char 指针只能在使用旧接口时代替 std::string,或者(仅在极端情况下)用于优化目的。
  • 感谢 George 和 TheDude。我同意。删除了评论。

标签: c++ variables


【解决方案1】:

你所拥有的不是一个字符串,而是一个字符 array 初始化 with 一个字符串文字。在 C++ 中处理字符串的惯用方式是利用标准 std::string 类型并调用其 constructors 之一,例如接受 std::initializer 列表的那个:

std::string word{"computer"};

或复制构造函数:

std::string word("computer");

或使用字符串operator=string literal 的值分配给您的变量。

std::string word;
word = "computer";

确保包含&lt;string&gt; 标头:

#include <iostream>
#include <string>
int main() {
    std::string word{ "computer" }; // starting with C++11
    std::string word2("computer 2");
    std::string word3;
    word3 = "computer 3";
    std::cout << word << '\n';
}

【讨论】:

  • 不能让它工作。你能解释一下吗?例如变量“word”的名称去哪儿了?
  • std::string 不是内置的,但是是标准的,足够接近了。
  • 上面写着[Error] in C++98 'word' must be initialized by constructor, not by '{...}'
  • C++98 标准不支持初始化列表。使用括号代替大括号。上述链接中最右侧的一列(绿色文本)表示标准和可用性。
  • @J_p 你为什么使用过期 20 年的标准?
猜你喜欢
  • 2022-11-27
  • 1970-01-01
  • 2013-05-27
  • 2023-03-04
  • 2020-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-23
相关资源
最近更新 更多