c++ - 使用字符串的变量将字符串拆分为字符数组

标签 c++ parsing split

我正在尝试将字符串拆分为单个字符的数组。但是,我希望用户输入字符串,为此我需要使用变量定义字符串。

我的问题是,为什么会这样:

#include <iostream>
using namespace std;
int main() {
char arr [] = {"Giraffe"};
cout << arr[0];
    return 0;
}

但这不是吗?
#include <iostream>
using namespace std;
int main() {
string word;
word = "Giraffe";
char arr [] = {word};
cout << arr[0];
    return 0;
}

谢谢

最佳答案

你的例子不起作用,因为你试图把 std::stringchar 的数组中.编译器会在这里报错,因为 std::string没有到 char 的类型转换.

由于您只是尝试打印字符串的第一个字符,因此只需使用数组访问器重载 std::string , std::string::operator[] 反而:

std::string word;
word = "Giraffe";
std::cout << word[0] << std::endl;

关于c++ - 使用字符串的变量将字符串拆分为字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53861917/

相关文章:

c++ - 获取 Clang 中变量的大小

c++ - 如何在 main 中使用指针数组?

java - 如何从 SOAP 响应中获取 xml 元素的值? (安卓)

javascript - 需要根据jquery中给定的数值分割字符串

bash - 从包含正斜杠的 bash 中的变量中删除字符串的一部分

javascript - 将 Javascript 数组元素拆分为指定索引处的 block

c++ - 从另一个 cpp 更新文本框值

c++ - 视觉 C++ 2005 x64?

algorithm - 如何将扩展巴科斯诺尔文法转换为其正常表示形式?

c++ - 在 C++ 中仅解析来自 istream 的数字