Thread: infinite loop

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Aug 2011
    Posts
    385

    infinite loop

    why does the following code gets stuck in an infinite loop in the second pass through the while loop?? I know its got something to do with the input buffer, cause it works when I use fflush(stdin) but I can't understand what's wrong. Also I need to know why std::cout.flush() does not seem to be working..

    Code:
    #include <iostream>
    #include <fstream>
    
    int main()
    {
    	std::ofstream file;
    	file.open("file.dat",std::ios::trunc|std::ios::binary);
    	if(!file)
    		std::cout<<"unable to open for output";
    
    	struct record
    	{
    		char code[6];
    		char name[20];
    		int i;
    	};
    
    	record r;
    	int a = 0;
    
    	while(1)
    	{
    		std::cout<<"Record " << a + 1 << std::endl;
    		std::cout<<"Enter character code, name and an int \n";
    		std::cin.getline(r.code,6);
    		std::cout.flush();
    		std::cin.getline(r.name,20);
    		std::cout.flush();
    		std::cin>>r.i;
    		std::cout.flush();
    		file.write((char *)&r,sizeof(r));
    		std::cout<<"\nAdd another (y\\n) : ";
    		char c;
    		std::cin>>c;
    		std::cout.flush();
    		if(c == 'n')
    			break;
    		a++;
    		std::cout<<'\n'<<'\n';
    	}
    	file.close();
    }
    Last edited by juice; 03-18-2012 at 01:23 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. infinite loop
    By juice in forum C Programming
    Replies: 9
    Last Post: 12-18-2011, 12:16 PM
  2. Replies: 3
    Last Post: 10-14-2011, 11:33 PM
  3. Infinite loop!!!
    By Bizmark in forum C Programming
    Replies: 3
    Last Post: 02-21-2009, 12:09 PM
  4. stays in loop, but it's not an infinite loop (C++)
    By Berticus in forum C++ Programming
    Replies: 8
    Last Post: 07-19-2005, 11:17 AM
  5. Infinite Loop!!!
    By Frantic- in forum C++ Programming
    Replies: 3
    Last Post: 12-13-2004, 06:39 PM