如何修复向量不从文件打印值

How to fix vector not printing values from file

本文关键字:文件 打印 何修复 向量      更新时间:2023-10-16

我试图从文本文件中逐行获取一些值:

17.09 284.60 486.01 34.12 12.04 1.20 2.33 36.85 73.44
31.25 196.09 323.26 69.76 47.33 79.82 11.42 27.97 66.61
28.76 41.45 992.29 1.29 42.33 10.83 19.16 5.86 1.88

取这些值并将其放入向量。每行都有在计算中使用的值。

我的代码:

#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
#include <vector>
using namespace std;
int main() {
    ifstream xfile;
    string input;
    double num=0;
    int count = 0;
    vector <double> myvector;
    cout << "Input the file: ";
    cin >> input;
    xfile.open(input);
    if (xfile.is_open()) {
        cout << "File accessed!" << endl;
        while (getline(xfile, input)) {
            count++;
            myvector.push_back(num);
        }
    }
    else {
        cout << "File opening failed!"<<endl;
    }

    cout << "Numbers of lines in the file : " << count << endl;
    for (int i = 0; i < myvector.size(); i++) {
            cout << myvector[i] << "t";
        }
    cin.fail();
    return 0;
}

我的输出有些正确,只是它仅打印出零:https://ibb.co/xqwt1hr

编辑:输入是用于文件的名称。" ahu_long.txt"

您从未使用过num变量。

double num=0;
....
....
size_t pos = 0;
std::string token;
while (getline(xfile, input)) {
            count++;
            // you need convert your "input" to a double and save it to "num"
            while ((pos = input.find(" ")) != std::string::npos) {
                token = input.substr(0, pos);
                // std::cout << token << std::endl;
                num = atof(token.c_str());
                myvector.push_back(num);
                input.erase(0, pos + delimiter.length());
            }
        }

用文件从文件中更改变量。