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

x
  • 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.
0
klax33
Asked:
klax33
1 Solution
 
peter_sheynkmanCommented:
some code would be helpfull
0
 
KocilCommented:
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;

0
 
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;
  loc++;
}

If the first number was 15, v[0] would only have '1'.  I hope this helps illustrate my question.
0
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.
0
 
jadams117Commented:
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
0
 
klax33Author Commented:
Thank you for your help.
0

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