gpt4 book ai didi

c++ - 如何将字符串中的整数保存到数组中的元素

转载 作者:行者123 更新时间:2023-11-30 05:09:37 36 4
gpt4 key购买 nike

我试图实现的是使用 getline().txt 文件中逐行读取数据,并将其作为字符串保存到变量中输入值。然后,我想通过将字符串中的每个单独数字传递给成员函数 ArrayBag.add(value),将其保存到对象数组中的单独元素。到目前为止,我已经能够将数据读取到 inVal 中,但我尝试过的任何方法都无法转换和保存字符串中的数字,包括 getline( )。请提供任何指导或提示,我们将不胜感激。

.txt 文件如下所示:

 3  4  5  7  5 16 7 12 11 12  3  9  9  8  1 12
15 4 3 6 1 12 3 12 7 8 19 9 11 12 8 5 -4 -100

到目前为止我写的代码是这样的:

void readInv(ArrayBag &ArrayBag1, ArrayBag &ArrayBag2) {
//ArrayBag1 and ArrayBag2 are objects of class ArrayBag

std::string inVal;
//value to hold each line in file

std::ifstream readFile;
readFile.open("setInventory.txt"); //"setInventory.txt" is the txt file being read from.

if (readFile.is_open()) {
std::cout << "File is being read." << std::endl;

while(!readFile.eof()) {
getline(readFile, inVal);

for(int i = 0; i < inVal.size(); i++) {
std::cout << inVal[i] << std::endl;

ArrayBag1.add(inVal[i] - '0');
//ArrayBag1.add() is the public member function used to add the
//passing value to the private member array.
}
}
}
}

最佳答案

我想你可以使用 stringstream

  stringstream ss{readFile};
while(ss)
{
//doing something
int a;
ss>>a;
ArrayBag1.add(a);
}

关于c++ - 如何将字符串中的整数保存到数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46088724/

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