Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 215
  • Last Modified:

File I/O Question

I have a vector of type int of size N.  I am reading values from a file that contains 1 and 2 digit numbers into a variable of type char using indirection.  The problem is, when I want to read '15' I only get '1'.  I thought char was larger than int and the indirection would take care of getting a "whole" number.  Any help would be appreciated.
1 Solution
some code would be helpfull
char is smaller than int.
In fact, char is only 1 byte and int is 4 bytes.

From a file like this
15 16
and the code like this

  char a, b;
  cin >> a >> b;

the result will always a=1, b=5.

To get the result a=15, b=16,
you should use either

int a,b;
short int a,b;
long a,b;

klax33Author Commented:
vector<int> v(10);

char current;
int loc=0;

while (inFile)
  // file opened and at first location
  inFile >> current;
  // if current is a delimiter (comma) then skip it
  v[loc] = current;

If the first number was 15, v[0] would only have '1'.  I hope this helps illustrate my question.
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

klax33Author Commented:
When I change from char to int, inFile reads garbage values like -892345223.
You're reading a character (i.e. a letter) and then assigning it to a number. It's not surprising it doesn't work but your compiler should have given you a warning. To read in an integer use:

int number;
inFile >> number;

If each number is followed by a delimiter you'll need to read that in as a string. e.g.:

int number;
std::string str;
inFile >> number >> string;

If you need to do further checking (e.g. make sure the thing you're reading really is a valid integer) you should read everything in as a string and then do your checking before converting it into a number
klax33Author Commented:
Thank you for your help.

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now