Alter Ego
Alter Ego

Reputation: 39

To store tokens into an array

A novice at C++, i am trying to create a stats program to practice coding. i am hoping to get a text file, read it and store values into arrays on which i can perform mathematical operations. i am stuck here

 main ()
 {
      char output[100];
      char *charptr;
      int age[100];
      ifstream inFile;
      inFile.open("data.txt");
      if(!inFile)
      {
            cout<<"didn't work";
            cin.get();
            exit (1);
      }

      inFile.getline(output,100);
      charptr = strtok(output," ");
      for (int x=0;x<105;x++)
      {
           age[x] = atoi(charptr);
           cout<<*age<<endl;

      }

     cin.get();
}

in the code above, I am trying to store subject ages into the int array 'age', keeping ages in the first line of the file. I intend to use strtok as mentioned, but i am unable to convert the tokens into the array.

As you can obviously see, I am a complete noob please bear with me as I am learning this on my own. :)

Thanks

P.S: I have read similar threads but am unable to follow the detailed code given there.

Upvotes: 0

Views: 2111

Answers (1)

hmjd
hmjd

Reputation: 121971

There are a few issues with the for loop:

  • Possibility of going out-of-bounds due to age having 100 elements, but terminating condition in for loop is x < 105
  • No check on charptr being NULL prior to use
  • No subsequent call to strtok() inside for loop
  • Printing of age elements is incorrect

The following would be example fix of the for loop:

charptr = strtok(output, " ");
int x = 0;
while (charptr && x < sizeof(age)/sizeof(age[0]))
{
    age[x] = atoi(charptr);
    cout << age[x] << endl;
    charptr = strtok(NULL, " ");
    x++;
}

As this is C++, suggest:

  • using std::vector<int> instead of a fixed size array
  • use the std::getline() to avoid specifying a fixed size buffer for reading a line
  • use std::copy() with istream_iterator for parsing the line of integers

For example:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>

int main ()
{
    std::vector<int> ages;
    std::ifstream inFile;
    inFile.open("data.txt");
    if(!inFile)
    {
        std::cout<<"didn't work";
        std::cin.get();
        exit (1);
    }

    std::string line;
    std::getline(inFile, line);

    std::istringstream in(line);

    std::copy(std::istream_iterator<int>(in),
              std::istream_iterator<int>(),
              std::back_inserter(ages));

    return 0;
}

Upvotes: 5

Related Questions