-2

我正在尝试将 .txt 文件中的值读取到 C++ 中的向量(它是类的成员),但是尽管 .txt 有大约 1000 行,但向量的大小为 0。我插入了一个“cout”,我知道文件已打开和关闭。我不确定我做错了什么,因为代码不读取 .txt 的内容。

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cmath>
#include "option_class.h"
using namespace std;
int main(){
double cprice = 0.0;
int i = 0;
string line;
ifstream is;
is.open("/Users/<USER>/Desktop/SPY.txt");
if (!is){
    cout << "Unable to open file" << endl;
    return(0);
}
while(!getline(is, line).eof()){
    is >> cprice;
    option1.price.push_back(cprice);
}
is.close();
cout << "Closing file" << endl;
}
4

1 回答 1

0

您是否尝试过更简单的方法:

while (is >> cprice)
{
    option1.price.push_back(cprice);
}

operator>>跳过包含换行符的空格。无需一次读取一行。

于 2019-12-13T23:21:07.503 回答