将Vector <int>转换为String

dul*_*pat 4 c++ string vector

我想制作一个首先输入字符串数组的程序,然后将其转换为整数,然后将其推送到矢量.

代码是这样的:

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);
}
Run Code Online (Sandbox Code Playgroud)

输出 :

Enter the message = haha
Converted Message to integer = 104 97 104 97
Run Code Online (Sandbox Code Playgroud)

然后我把它写在一个文件中,在下一个程序中我想把它读回来,并将它转换回字符串,我的问题是如何做到这一点?将矢量[104 97 104 97]转换回字符串"haha".

我非常感谢任何帮助.谢谢.

Mr.*_*C64 6

[...]我的问题是如何做到这一点?将矢量[104 97 104 97]转换回字符串"haha".

这很容易.您可以循环遍历std::vector元素,并使用std::string::operator+=重载将结果字符串中的字符(其ASCII值存储在其中std::vector)连接起来.

例如

#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;
}
Run Code Online (Sandbox Code Playgroud)

控制台输出:

C:\TEMP\CppTests>g++ test.cpp

C:\TEMP\CppTests>a.exe
haha
Run Code Online (Sandbox Code Playgroud)

关于原始代码的一个小注释:

X =(int)的a.at(ⅰ);

您可能希望在代码中使用C++样式转换而不是旧的C样式转换(即static_cast在上面的代码中).

此外,因为你知道向量的大小,你应该也知道,有效的指标,从去0(size-1),所以使用简单快捷,高效的std::vector::operator[]过载是蛮好的,而不是使用std::vector::at()方法(与它的索引边界检查开销).

所以,我会改变你的代码:

x = static_cast<int>( a[i] );
Run Code Online (Sandbox Code Playgroud)


kha*_*vah 5

 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;

}
Run Code Online (Sandbox Code Playgroud)