【问题标题】:how to save ints in a string to elements in array如何将字符串中的整数保存到数组中的元素
【发布时间】: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.
            }
        }
    }
}

【问题讨论】:

标签: c++ arrays casting ifstream


【解决方案1】:

我认为你可以使用stringstream

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2015-02-08
    • 2021-08-01
    相关资源
    最近更新 更多