Thread: Char[1024] to char

  1. #1
    Registered User
    Join Date
    Mar 2011
    Posts
    21

    Char[1024] to char

    I have written the following code (names file is fine and that is not the issue. It is the old chesnut of converting char, char*, string arrays.

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	FILE *txtfile;
    	char line[1024];
    	char studentlist[6];
    	int pos=0;
    
    	if((txtfile=fopen("Names.DAT","r"))==NULL)
    		exit(-1);
    
    	cout << "The names in the text file are:" << endl;
    	cout << endl;
    
    	while(fgets(line,1024,txtfile)!=NULL)
    		
    		//cout << line;
    		studentlist[0]=line;
    		cout << studentlist[0];
    
    	fclose(txtfile);
    	cin.get();
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    So why not go all the way to C++, use C++ streams, and use C++ std::string to store the information you read.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    template<typename T> threahdead's Avatar
    Join Date
    Sep 2002
    Posts
    214
    Quote Originally Posted by musicman View Post
    I have written the following code (names file is fine and that is not the issue. It is the old chesnut of converting char, char*, string arrays.

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	FILE *txtfile;
    	char line[1024];
    	char studentlist[6];
    	int pos=0;
    
    	if((txtfile=fopen("Names.DAT","r"))==NULL)
    		exit(-1);
    
    	cout << "The names in the text file are:" << endl;
    	cout << endl;
    
    	while(fgets(line,1024,txtfile)!=NULL)
    		
    		//cout << line;
    		studentlist[0]=line;
    		cout << studentlist[0];
    
    	fclose(txtfile);
    	cin.get();
    }
    The line marked in red is assigning a char * to a char. This will get you a compile time error.

    You should, like Salem said, use C++ streams and std::string for the studentlist.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 12-08-2009, 02:47 AM
  2. Read File To Char Array with Null char init
    By MicroFiend in forum Windows Programming
    Replies: 1
    Last Post: 10-28-2003, 06:18 PM
  3. Assigning Const Char*s, Char*s, and Char[]s to wach other
    By Inquirer in forum Linux Programming
    Replies: 1
    Last Post: 04-29-2003, 10:52 PM
  4. declaring chars: char file[<nonconstant>] [1024];
    By jverkoey in forum C++ Programming
    Replies: 9
    Last Post: 03-30-2003, 01:47 AM
  5. char[1024] to c++ STL string
    By dkt in forum C++ Programming
    Replies: 1
    Last Post: 05-08-2002, 08:13 AM

Tags for this Thread