reading into an int

This is a discussion on reading into an int within the C++ Programming forums, part of the General Programming Boards category; Is there a way to only read in a certain amount (2 in this case) of numbers into an int? ...

  1. #1
    Registered User Cpro's Avatar
    Join Date
    Oct 2006
    Posts
    149

    reading into an int

    Is there a way to only read in a certain amount (2 in this case) of numbers into an int?
    For example, my input looks like:
    Code:
    04Will05Smith0825 Place05Tulsa02OK0538135
    05Corey05Black10Elm Street06Dallas02TX0589148
    So, i want to read only two numbers into an int variable. Currently, my program reads all numbers until it hits a non-int character. So, when it gets to the address entry:
    Code:
    0825 Place
    It will read 0825 into the variable, instead of 08.
    Here is my code:
    Code:
    istream & operator >> (istream & stream, Person & p)
    {		
    	
    	int length = 0;	
    	
    	stream >> length;
    	length++;
    	stream.get(p.firstName, length);
    	stream.ignore();
    
    	stream >> length;
    	length++;
    	stream.get(p.lastName, length);
    	stream.ignore();
    
    	stream >> length;
    	length++;
    	stream.get(p.address, length);
    	stream.ignore();
    
    	stream >> length;
    	length++;
    	stream.get(p.city, length);
    	stream.ignore();
    
    	stream >> length;
    	length++;
    	stream.get(p.state, length);
    	stream.ignore();
    
    	stream >> length;
    	length++;
    	stream.get(p.zipCode, length);
    	stream.ignore();
    	
    	return stream;
    }
    My output is fine until it hits the address.
    I've tried declaring a char and typecasting and using atoi, but i still can't get it to work.

    Thanks.
    IDE - Visual Studio 2005
    Windows XP Pro

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,340
    You'll probably want to get the two characters one at a time and then convert them to an int. You can use a stringstream or just do it manually with math ((char_one-'0') * 10 + (char_two-'0')).

  3. #3
    Registered User Cpro's Avatar
    Join Date
    Oct 2006
    Posts
    149
    Thanks. That fixed it.
    IDE - Visual Studio 2005
    Windows XP Pro

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. memory leak
    By aruna1 in forum C++ Programming
    Replies: 3
    Last Post: 08-17-2008, 10:28 PM
  2. Replies: 8
    Last Post: 03-10-2008, 11:57 AM
  3. Replies: 3
    Last Post: 05-13-2007, 08:55 AM
  4. Working with random like dice
    By SebastionV3 in forum C++ Programming
    Replies: 10
    Last Post: 05-26-2006, 09:16 PM
  5. Quack! It doesn't work! >.<
    By *Michelle* in forum C++ Programming
    Replies: 8
    Last Post: 03-01-2003, 11:26 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21