【发布时间】:2017-09-07 05:49:56
【问题描述】:
我试图实现的是使用getline()逐行从.txt文件中读取数据,并将其作为字符串保存到变量inVal中。然后,我想通过将字符串中的每个单独的数字传递给成员函数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.
}
}
}
}
【问题讨论】:
-
离题(但会解决即将到来的错误):Why is iostream::eof inside a loop condition considered wrong?
-
Read file line by line 的可能重复项。具体回答1选项2。
-
您是否有理由不能为此使用
std::vector?向量比数组好得多。 -
在这里查看热门答案:stackoverflow.com/questions/236129/…
-
@Sailanarmo 分配禁止使用向量,ArrayBag 类的工作方式类似于自定义向量,但应该使用它。
标签: c++ arrays casting ifstream