Extract numbers as integers from a string array

This is a discussion on Extract numbers as integers from a string array within the C++ Programming forums, part of the General Programming Boards category; Here is my main() Code: void main() { ifstream inFile; char buffer[80]; int year, month, day; inFile.open("birthday.txt",ios::in|ios::nocreate); if(inFile.fail()) { cout ...

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    1

    Extract numbers as integers from a string array

    Here is my main()
    Code:
    void main()
    {
    	ifstream inFile;
    	char buffer[80];
    	int year, month, day;
    
    	inFile.open("birthday.txt",ios::in|ios::nocreate);
    
    	if(inFile.fail())
    	{
    		cout << "birthday.txt could not be opened";
    		exit(1);
    	}
    	
    	inFile.getline(buffer,80,'\n');
    	
    }
    Now what is in buffer is 2002 3 20 a date
    I want to put 2002 into year an integer variable and month and day as well.

    Thanks DarthC

  2. #2
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    Code:
    #include <strstream>
    #include <fstream>
    #include <iostream>
    #include <cstdlib>
    
    void main()
    {
            std::ifstream inFile;
            char buffer[80];
            int year, month, day;
    
            inFile.open("birthday.txt",ios::in|ios::nocreate);
    
            if(inFile.fail())
            {
                    std::cout << "birthday.txt could not be opened";
                    exit(1);
            }
    
            inFile.getline(buffer,80,'\n');
    
    	std::istrstream inStream(buffer);
    	inStream >> year >> month >> day;
    	std::cout << year << " " << month <<  " " << day << std::endl;
    }
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  3. #3
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    Or you could skip the strstream. If the date is in the format you've specified write directly into the variables-

    inFile >> year >> month >> day;

    instead of using getline().

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 03:13 PM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 04:45 PM
  3. can't assign proper values to an array of string
    By Duo in forum C Programming
    Replies: 1
    Last Post: 04-04-2005, 06:30 AM
  4. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  5. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-26-2003, 11:03 PM

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