gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:53:19 25 4
gpt4 key购买 nike

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

每行只有两个数字(整数),另一个 vector 的 X 和 Y 位置。这个想法是将每个整数分配给 vector 中的相应变量。我没能做到那么远,因为我无法让它超过第 1 行。但我认为通过数组大小为 2,数组临时存储值,将其分配给 vector ,然后用下一个可以工作的值覆盖它。但又没能做到那么远。

下面是我一直在尝试使用的代码;

........
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 循环将根据需要将结果分配给其他 vector 变量。任何帮助表示赞赏:)

最佳答案

使用两个 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>

关于c++ - 如何在多行 C++ 中将字符串拆分为两个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22599816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com