C - 将向量值分配给std :: String而不会丢失数据
C++ - assign Vector value to std::string without losing data
我想将int矢量的值分配给std ::字符串以传递到另一个函数,因为我现在写了此代码:
int input;
std::cout << "Insert the value to convert: t";
std::cin >> input;
std::string output;
std::vector<int> rem;
int r; //Just a simple binary conversion
while(input != 0) {
r = input % 2;
rem.push_back(r);
input /= 2;
}
std::reverse(rem.begin(), rem.end());
for(std::vector<int>::const_iterator it = rem.begin(); it != rem.end(); ++it) {
output += *it; //Assign every value of the iterator to string variable
}
std::cout << output; Print the value of output
我的代码问题是字符串包含诸如☺ ☺☺☺ ☺☺☺☺ ☺
之类的奇怪字符...是否有任何方法可以防止?
为什么在添加到输出时不会将int转换为字符串?尝试以下操作:
std::stringstream ss;
ss << *it;
std::string str = ss.str();
output += str; //Assign every value of the iterator to string variable
您实际上不需要尝试实现的数据附加副本:
std::string output;
while(input) {
output += (input % 2 ? "1" : "0");
input /= 2;
}
std::reverse(std::begin(output), std::end(output));
std::cout << output;
我想按顺序将int矢量的值分配给std :: string 要将其传递到另一个功能,现在我编写了此代码:
您的问题是整数可隐式转换为char。代码output += *it;
有效地暗示了类似的内容:
char& i = *it;
i = 1; //Compiles, but how is 1 represented (1 != '1')
//considering encoding etc?
我以功能方法对此进行了刺伤。您只需用std :: ostringstream实例替换std :: cout并获取其字符串。
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
int main() {
std::cout << "Insert the value to convert: t";
std::vector<int> rem;
// Get user input...
std::copy_if(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),
std::back_inserter(rem), [](int val) {return val != 0;});
//Do your transforation
std::transform(rem.begin(), rem.end(), rem.begin(), [](int i){return i % 2; });
//And reverse and copy to stream...
std::reverse(rem.begin(), rem.end());
std::copy(rem.begin(), rem.end(), std::ostream_iterator<int>(std::cout, " "));
}
注意:我同意其他两个答案,但也认为这个答案突出了这个问题。
相关文章:
- 从 std::string 到 std::array<char,size> 的 memcopy 额外数据是否是一种未定义的行为?
- 面对迭代矢量<矢量<string>>和打印数据的问题
- 比较存储在 std::string 中的数据中的字节数
- 自定义堆栈上 std::string 数据的输出
- 存储指向 std::string 数据的指针是否安全?
- 如何使用矢量数据使用 rapidjson 库创建 json 文件<string>?
- UTF8 数据到 std::string 或 std::wstring
- 如何有效地将底层数据从 std::string 移动到其他类型的变量?
- 数据结构对齐:为什么Char和STD :: String的数组不同
- C - 将向量值分配给std :: String而不会丢失数据
- Python 数据结构:map<string、vector<int>>
- C 11 STD :: Promise返回STD :: String从线程中返回String,数据指针看起来已复制
- 从 std::string C++中提取任意数据值
- 我想从文件中读取数据块并将其存储在矢量<string> buf 中。我做错了什么?
- 特征库 --> 使用文件或现有 std::vector<string> content (c++) 中的数据初始化矩阵
- gSOAP:RPC截断std::string中的二进制数据
- 将const char*转换为std::string时缺少数据
- 如何在不复制和保留 std::string 对象的情况下获得 C++ std::string 字符数据的所有权
- 在 std::vector 的构造函数中使用 std::string 数据类型
- 为什么在c++中,当等价相同的文本值时,char和string数据类型显示不同的结果?