-2

I am trying to get some values line by line from a text file:

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

Taking these values and putting it into a vector. Each row has values to be used in a calculation.

My code:

#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;
}

My output is somewhat correct, only that it is printing out just zeroes: https://ibb.co/xqwT1hR

EDIT: the input is for the name of file. "ahu_long.txt"

Master Irfan Elahee
  • 165
  • 1
  • 1
  • 14

1 Answers1

1

You never used your num variable.

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());
            }
        }

Change your variable with what you read from the file.

Celal Ergün
  • 955
  • 2
  • 14
  • 30