Ok, well I am new to c++ and have been trying to get the basics down. I have a class assingment which require me to read numbers from a file and store them into a vector as long int. An example of the file would be :


I started and got it compiled, but only got 1 number and the rest 0. So I did research and found out i might have to change it to a string first and then back to long int. but i'm having a hard time figuring it out. I have posted my code, which does have some things that might not belong in comments right now, but i had to test it. If someone has a better idea and can explain why im having a hard time changing string to long int, please advise me

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

int main(){
    char temp[100];
    char line;
    long int x;
    long int num;
    int y=0;
    vector<long int> dateList(11);

    ifstream inFile;

    /*if (!inFile) {
        cerr << "Unable to open file datafile.txt";
        exit(1);   // call system to stop

    while(inFile >> x){
        num = atoi(line);
        //num = strtol(line,0,11);
        dateList[y] = num;

    for (int i=0; i < dateList.size(); i++)
        cout << dateList[i] << " ";


    cin >> x;
    return 0;


Edited 3 Years Ago by pritaeas: Fixed formatting

stdlib's atol() not atoi().

int countlines;
inFile.getline(temp, 100);
alongarray[countlines] = atol(temp);
countlines += 1;

Good enough.

What kind of variable would "temp" be?? And is there a way to get it directly to the vector i have declared?

This article has been dead for over six months. Start a new discussion instead.