CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 15

Threaded View

  1. #6
    Join Date
    Sep 2010
    Posts
    66

    Re: Extracting a line from content in the line

    Quote Originally Posted by wiec7548 View Post
    And I don't quite understand that loop, the while(cin) part is throwing me, wouldn't that just make the program continue forever? Because the keyboard will always be active? What if I have an option included for exit the program?
    In the above example, notice that if the user enters a word beginning with q (ie, quit) the program returns from main:

    Code:
    		case 'Q': 
    			cout << "Goodbye";
    			return 0;
    As for the while(cin), you can check the state of an input stream like this. The stream will be put in a fail state if the user enters the wrong type of data (ie, if the user enters a character where an int is expected) or if eof is encountered (you can simulate this by pressing control-C in windows).

    As for how to do it, here is one way:

    Code:
    #include <string>
    #include <fstream>
    
    using namespace std;
    
    
    struct Person{
    	string name,
    		number,
    		address;
    };
    
    int main () {
    	Person addressBook[50];
    	Person temp;
    
    	ifstream infile("test.txt");
    
    	if(!infile){
    		cout << "Error opening input file" << endl;
    		return -1;
    	}
    
    	for(int i = 0; infile >> temp.name >> temp.number  && i < 50; i++){
    		infile.ignore(1);
    		if(getline(infile, temp.address, '\n'))
    		addressBook[i] = temp;
    	}
    
    return 0;
    }
    This assumes your input file is like so:

    Code:
    Joe 221-1150 20 Jackall Road
    Tom 225-6699 2051 Lane Drive
    Jospeh 115-1410 2222 Smith Road
    Again this isn't the best because it will only be able to hold at most 50 entries. Anyway, after you have read everything you want into the array, you can then let the user do what they want to do and modify the array when the program is running. Before exiting, open the file by creating an ofstream object using the filename and write the contents of the array to the file.
    Last edited by ttrz; October 31st, 2010 at 09:05 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured