如何将字符串拆分为多行C ++中的两个整数

时间:2014-03-24 01:56:16

标签: c++ vector split

我一直在尝试从文本文件中检索已保存的数据。存储的数据都是数字,用〜分隔。我设法让它打印出其中一行(顶行),但我还是无法弄清楚如何处理整个文件。

每行只有两个数字(整数),另一个向量的X和Y位置。我们的想法是将每个整数分配给向量中的相应变量。我没有成功,因为我无法通过第1行。但我认为通过使数组大小为2,并且数组暂时存储该值,将它分配给向量,然后用可能有效的下一个值覆盖它。但再次没有成功到那么远。

以下是我一直试图使用的代码;

........
string loadZombieData;
loadFile >> loadZombieData; //Data gets read from the file and placed in the string

vector<string>   result; //Stores result of each split value as a string


stringstream  data(loadZombieData);
string line;
while(getline(data,line,'~'))
{
    result.push_back(line); 
}

for(int i = 0; i < result.size(); i++){
    cout << result[i] << "  ";
}
.......

只是为了澄清,这不是我的代码,这是我在Stackoverflow上找到的一些代码,所以我还不完全确定它是如何工作的。正如我所说,我一直试图让它读取多行,然后使用for循环将根据需要将结果分配给其他矢量变量。任何帮助表示赞赏:)

1 个答案:

答案 0 :(得分:0)

使用两个while循环:

std::vector<std::string> result;
std::vector<int> numbers;

std::string filename;
std::ifstream ifile(filename.c_str());

if (!ifile.is_open()) {
    std::cerr << "Input file not opened! Something went wrong!" << std::endl;
    exit(0);
}

std::string temp;

//loop over the file using newlines as your delimiter
while (std::getline(ifile, temp, '\n')) {
   //now temp has the information of each line.
   //create a stringstream initialized with this information:

   std::istringstream iss(temp);//this contains the information of ONE line

   //now loop over the string stream object as you would have in your code sample:
   while(getline(iss, temp,'~'))
   {
       //at this point temp is the value of a token, but it is a string
       result.push_back(temp); //note: this only stores the TOKENS as strings

       //so to store the token as a int or float, you need to convert it to that
       //via another stringstream:

       std::istringstream ss(temp);

       //if your number type is float, change it here as well as in the vector
       //initialization of `numbers`:
       int num = 0;
       //this checks the stream to ensure that conversion occurred.
       //if it did, store the number, otherwise, handle the error (quit - but, this is up to you)
       //if stringstreams aren't your cup of tea, try some others (refer to this link):
       //http://stackoverflow.com/questions/21807658/check-if-the-input-is-a-number-or-string-c/21807705#21807705
       if (!(ss >> num).fail()) {
           numbers.push_back(num);
       }
       else {
           std::cerr << "There was a problem converting the string to an integer!" << std::endl;
       }
    }
}

注意:此版本逐字存储数字:即不知道一行中有多少个数字。但是,这是可以协调的,因为你所要做的就是每行输出n个数字。在您的情况下,您知道每2个数字代表一行中的数字。

这需要:

#include <string>
#include <vector>
#include <cstdlib>
#include <sstream>