【问题标题】:How to Convert String to Vector [duplicate]如何将字符串转换为向量 [重复]
【发布时间】:2013-08-22 13:16:31
【问题描述】:

我正在写两个程序,第一个程序有一个整数数组

vector<int> v = {10, 200, 3000, 40000};

然后它将向量转换为字符串

int i;
stringstream sw;
string stringword;

for (i=0;i<v.size();i++) 
{
    sw << v[i] << ',';
}
stringword = sw.str();
cout << "Vector in string : "<< stringword << endl;

然后写到一个文件里

ofstream myfile;
myfile.open ("writtentext");
myfile << stringword;
myfile.close();

输出:

Vector in string : 10,200,3000,40000

第二个程序将读取文件,将字符串转换回整数,然后将其推回向量。

代码:

string stringword;

ifstream myfile;
myfile.open ("writtentext");
getline (myfile,stringword);
cout << "Read From File = " << stringword << endl;

cout << "Convert back to vector = " ;
for (int i=0;i<stringword.length();i++)
{
    if (stringword.find(','))
    {
        int value;
        istringstream (stringword) >> value;
        v.push_back(value);
        stringword.erase(0, stringword.find(','));
    }
}
for (int j=0;j<v.size();j++) 
{
    cout << v.at(j) << " " ;
}

问题是,它只能转换并推回第一个元素,其余的都被擦除了。这是输出:

Read From File = 10,200,3000,40000,
Convert back to vector = 10

我做错了什么?谢谢

【问题讨论】:

标签: c++ string vector converter


【解决方案1】:

你的 for 循环有问题

考虑一下:

while(1) //Use a while loop, "i" isn't doing anything for you
{
    //if comman not found find return string::npos

    if (stringword.find(',')!=std::string::npos)
    {
        int value;
        istringstream (stringword) >> value;

        v.push_back(value);

       //Erase all element including comma
        stringword.erase(0, stringword.find(',')+1);
    }
    else 
       break; //Come out of loop
}

相反,只需使用std::stringstream 从文件中读回

std::stringstream ss(stringword);
int value;
while (ss >> value)
{
    v.push_back(value);

    if (ss.peek() == ',')
        ss.ignore();
}

for (int j=0;j<v.size();j++)  //Fix variables
{
    cout << v.at(j) << " " ; // Can use simply v[j]
}

【讨论】:

    【解决方案2】:
    for (int j=0;j<v.size();i++) 
    {
        cout << v.at(i) << " " ;
    }
    

    应该是

    for (int j=0;j<v.size();j++) 
    {
        cout << v.at(j) << " " ;
    }
    

    i 未在 for 循环中声明

    【讨论】:

    • 正确,但这不是问题
    【解决方案3】:

    您可以跳过字符串转换。所有流都可以处理int 类型。

    std::vector&lt;int&gt; 输出:

    #include <iostream>
    #include <iterator>
    #include <vector>
    
    int main() {
        std::vector<int> v;
        v.push_back(1);
        v.push_back(2);
        v.push_back(3);
        v.push_back(4);
        std::ostream_iterator<int> output_iterator(std::cout, ",");
        std::copy(v.begin(), v.end(), output_iterator);
    }
    

    输入std::vector&lt;int&gt;:

    #include <iostream>
    #include <vector>
    #include <sstream>
    using namespace std;
    
    int main() {
        std::vector<int> v;
        int value;
    
        std::string line;
        while(getline(cin, line, ',')) {
            std::stringstream ss(line);
            ss >> value
            v.push_back(value);
        }
        typedef std::vector<int>::iterator iter;
        iter end = v.end();
        for(iter it = v.begin(); it != end; ++it) {
            std::cout << *it << endl;
        }
    }
    

    【讨论】:

      【解决方案4】:

      这只是你犯的一个错误:

      for (int j=0;j<v.size();i++) 
      {
          cout << v.at(i) << " " ;
      }
      

      但是这里的工具效率太低了:

      for (int i=0;i<stringword.length();i++)
      {
          if (stringword.find(','))
          {
              int value;
              istringstream (stringword) >> value;
              v.push_back(value);
              stringword.erase(0, stringword.find(','));
          }
      }
      

      你可以这样做,只是一个建议:

      #include <iostream>
      #include <string>
      #include <vector>
      #include <stdlib.h>
      
      int ConvertStringToInt(const std::string &str, std::vector<int> &ints)
      {
          int count_int = 0;
          std::string string_int;
      
          size_t start = 0;
          size_t end   = 0;
      
          while ((end = str.find(',', start)) != std::string::npos)
          {
              string_int.assign(str, start, end - start);
              ints.push_back(atoi(string_int.c_str()));
              start = end + 1;
              ++count_int;
          }
          if (start != str.size())
          {
              ints.push_back(atoi(str.c_str() + start));
              ++count_int;
          }
          return count_int;
      }
      
      int main(int argc, char *const argv[]) 
      {
          std::vector<int> ints;
          std::string str = "123,456,789 ";
          std::cout << ConvertStringToInt(str, ints) << std::endl;
          for (size_t i = 0; i != ints.size(); ++i)
          {
              std::cout << ints[i] << std::endl;
          }
          return 0;
      }
      

      【讨论】:

        【解决方案5】:

        你可以让你的程序更简单:

        #include <algorithm>
        #include <fstream>
        #include <iostream>
        #include <iterator>
        #include <vector>
        
        // output
        int main()
        {
            // my compiler doesn't support initializer lists yet :(
            std::vector<int> v(4);
            v[0] = 10;
            v[1] = 200;
            v[2] = 3000;
            v[3] = 40000;
        
            std::ofstream fout("mytestfile.txt");
            std::copy(v.begin(), v.end(), std::ostream_iterator<int>(fout, ","));
            fout.close();
            return 0;
        }
        
        // input
        struct int_reader : std::ctype<char>
        {
            int_reader() : std::ctype<char>(get_table()) {}
        
            static std::ctype_base::mask const* get_table()
            {
                static std::vector<std::ctype_base::mask> rc(table_size, std::ctype_base::mask());
                rc[','] = std::ctype_base::space;
                rc['\n'] = std::ctype_base::space;
                return &rc[0];
            }
        };
        
        int main()
        {
            std::vector<int> v;
            std::ifstream fin("mytestfile.txt", std::ifstream::in);
            fin.imbue(std::locale(std::locale(), new int_reader()));
            std::copy(std::istream_iterator<int>(fin), std::istream_iterator<int>(), std::back_inserter<std::vector<int>>(v));
            fin.close();
        
            std::cout << "You read in:  ";
            std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
            return 0;
        }
        

        【讨论】:

          【解决方案6】:

          虽然这是手工制作而不是使用std::stringstream,但我觉得它很容易理解。

          std::vector<std::string> StringToVector (const std::string s,
                                                   const char token)
          {
            std::vector<std::string> v;
          
            size_t posLast = 0, pos = 0;
            while((pos = s.find(token, pos)) != std::string::npos)
            {
              if(s[pos] != s[posLast])
                v.push_back(s.substr(posLast, pos - posLast));
              posLast = ++pos;
            }
            if(s[posLast] != 0)  // If there is no terminating token found
              v.push_back(s.substr(posLast));
          
            return v;
          }
          

          Demo 带有各种测试用例。

          【讨论】:

            猜你喜欢
            • 2019-02-07
            • 1970-01-01
            • 2021-09-19
            • 2016-05-03
            • 2019-10-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-05-21
            相关资源
            最近更新 更多