Ryan Seitz
Ryan Seitz

Reputation: 1

Need help reading in a file with integers into an array

The below code is not reading the correct chars from the file. Any idea what is wrong?

    ifstream inFile;
    inFile.open("chars.txt");

    char ch; //dummy variable
    char first, last;
    int first1, last1;

    for(int i=0;i<SIZE;i++)
    {
        for(int j=0;j<5;j++){
        inFile.get(first);
        inFile.get(last);

at this point first and last are not the correct chars from the file. (on the first run through the loop) It is probably something simple, but I am really bad at this. Thanks in advance.

Upvotes: 0

Views: 222

Answers (2)

Bill
Bill

Reputation: 14695

You don't need to parse the numbers manually like that. Instead of using the get function, I'd recommend using the extraction operator >>, like in the following example:

#include <vector>
#include <fstream>
#include <iostream>

int main()
{
  std::vector<int> values;
  std::ifstream inFile("chars.txt");
  int temp;

  // Read the values in one at a time:
  while (inFile >> temp)
  {
    values.push_back(temp);
  }

  // Demonstrate that we got them all by printing them back out:
  for (unsigned int i = 0; i < values.size(); ++i)
  {
    std::cout << "[" << i << "]: " << values[i] << std::endl;
  }
}

Upvotes: 1

Jeff
Jeff

Reputation: 12183

I am not sure if this applies to C++, but I had this problem in C#.

I had to use Char.GetNumericValue(); on the character being read.

Sample code in C#:

int myInt;
char myChar = '5';

myInt = Char.GetNumericValue(myChar);
Console.WriteLine("My character as int: "+myInt.ToString());

Upvotes: 0

Related Questions