我想创建一个首先输入字符串数组的程序,然后将其转换为整数,然后将其推送到矢量。
代码是这样的:
string a;
vector<long long int> c;
cout << "Enter the message = ";
cin >> a;
cout << endl;
cout << "Converted Message to integer = ";
for (i=0;i<a.size();i++)
{
x=(int)a.at(i);
cout << x << " "; //convert every element string to integer
c.push_back(x);
}
输出:
Enter the message = haha
Converted Message to integer = 104 97 104 97
然后我把它写在一个文件中,在下一个程序中我要读回来,然后将它转换回字符串,我的问题是如何做到这一点?将矢量[104 97 104 97]转换回字符串“haha”。
我非常感谢任何帮助。 感谢。
答案 0 :(得分:6)
[...]我的问题是如何做到这一点?转换载体[104 97 104 97]回到字符串“哈哈”。
这很容易。您可以遍历std::vector
元素,并使用 std::string::operator+=
重载将字符(其ASCII值存储在std::vector
中)连接到结果字符串中。< / p>
e.g。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<int> v = {104, 97, 104, 97};
string s;
for (auto x : v)
{
s += static_cast<char>(x);
}
cout << s << endl;
}
控制台输出:
C:\TEMP\CppTests>g++ test.cpp C:\TEMP\CppTests>a.exe haha
关于原始代码的简短说明:
X =(int)的a.at(ⅰ);
您可能希望在代码中使用 C ++风格的强制转换而不是旧的C风格的强制转换(例如,在上面的代码中为static_cast
)。
此外,既然你知道了向量的大小,你也应该知道有效索引从0
到(size-1)
,所以使用简单快速有效的std::vector::operator[]
重载就好了而不是使用std::vector::at()
方法(带有索引边界检查开销)。
所以,我会改变你的代码:
x = static_cast<int>( a[i] );
答案 1 :(得分:4)
std::vector<int> data = {104, 97, 104, 97};
std::string actualword;
char ch;
for (int i = 0; i < data.size(); i++) {
ch = data[i];
actualword += ch;
}
答案 2 :(得分:3)
#include <algorithm>
#include <iostream>
int main()
{
std::vector<int> v = { 104, 97, 104, 97 };
std::string res(v.size(), 0);
std::transform(v.begin(), v.end(), res.begin(),
[](int k) { return static_cast<char>(k); });
std::cout << res << '\n';
return 0;
}
两个注释:
std::vector<char>
- 这样可以简化此任务,static_cast<char>(k)
可能会有危险。reinterpret_cast
,但在您的情况下,static_cast
也可以使用const
。 C风格的演员阵容会做很多不好的事情,比如暗示{{1}}施放或卖掉你的灵魂。答案 3 :(得分:3)
使用std::string
的迭代器构造函数:
std::vector<long long int> v{'h', 'a', 'h', 'a'}; //read from file
std::string s{std::begin(v), std::end(v)};
std::cout << s; //or manipulate how you want
它确实提出了为什么你的向量包含long long int
时它应该只存储字符的问题。在尝试将其转换为字符串时请注意这一点。
答案 4 :(得分:1)
您可以使用自己的函数对象或lambda函数使用std :: transform进行反向转换,即(char)(int)。