简单的问题(在C++中):
如何将字符转换为字符串.所以例如我有一个字符串str ="abc";
我想提取第一个字母,但我希望它是一个字符串而不是一个字符.
我试过了
string firstLetter = str[0] + "";
Run Code Online (Sandbox Code Playgroud)
和
string firstLetter = & str[0];
Run Code Online (Sandbox Code Playgroud)
两者都不起作用.想法?
我有一个char普通的老字,我想变成一个std::string. std::string(char)当然不存在.我可以创建一个char数组并将其复制,我可以通过字符串流或许多其他小环形路径.目前,我更喜欢boost::lexical_cast,但即使这对于这个简单的任务来说似乎太冗长了.那么首选方式是什么?
我正在尝试从具有std::stringas键的无序映射中接收值,其中一些字符串只包含一个字符.我的所有输入都来自于std::stringstream我从中获取每个值并将其转换为char,然后将其转换为字符串使用
std::string result {1, character};,根据文档和此答案,这似乎是有效的.
但是,当我这样做时,字符串前置\ x01(对应于值1).这使得在地图中找不到字符串.我的调试器还确认字符串大小为2,值为"\ x01H".
为什么会发生这种情况,我该如何解决?
#include <iostream>
#include <sstream>
#include <unordered_map>
int main()
{
const std::unordered_map<std::string, int> map = { {"H", 1}, {"BX", 2} };
std::stringstream temp {"Hello world!"};
char character = static_cast<char>(temp.get()); // character is 'H'
std::string result {1, character}; // string contains "\x01H"
std::cout << result << " has length " << result.size() << std::endl; // H has length 2
std::cout << map.at(result) << std::endl; …Run Code Online (Sandbox Code Playgroud) 我是在需要打印控制台窗口内的V @ genere广场参加一个个人项目,但我遇到了一些问题,打印功能,因为它偷偷内其他类的记忆,并打印出的字符串从他们的到来.
对于那些不知道什么是Vigenere广场的人来说,这是一张照片
这是我的代码:
static void square() {
string cipher[27];
cipher[0] = " | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z";
for (int i = 0; i < 26; i++) {
string tmp = (char)(i + 'A') + " |";
for (int j = 0; j < 26; j++) {
tmp += " " + …Run Code Online (Sandbox Code Playgroud) 我很困惑为什么range-for在我的例子中使用 ref ?
#include <vector>
#include <unordered_map>
using namespace std;
int main()
{
const unordered_map<char, string> d2c_map= { {'1', "abc"} };
const string digits{"1"};
vector<string> R;
for(const auto c : d2c_map.at(digits[0])) {
R.push_back(c); // <-------------------------???
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
错误表明 c 的类型是const char&:
error: no matching function for call to 'std::vector<std::__cxx11::basic_string<char> >::push_back(const char&)'
Run Code Online (Sandbox Code Playgroud)