CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Nov 2011
    Posts
    3

    c++ help array's and files

    Hello,
    I am trying to write a program in c++. I have a text file and I am reading the information in...then I am trying to store the information into and object array. Is it possible to do this without using a pointer and a vector?

    I found the following code while searching

    Code:
    object myobj[2];  //Define an array of objects from a class
    	
    
    	//string array[5]; //Array to save the line on
    	int loop=0; //Index of array
    	int loop2;
    	string line; //The line taken from the *.txt source
    	ifstream myfile ("example.txt"); //To read from the *.txt File
    	if (myfile.is_open()) //Checking if the file can be opened
    	{
    		while (! myfile.eof() ) //Runs while the file is NOT at the end
    		{
    			getline (myfile,line); //Gets a single line from example.txt
    			myobj[loop]=line; //Saves that line in the array
    			loop++; //Does an increment to the variable 'loop'
    		}
    		myfile.close(); //Closes the file
    	}
    	else cout << "Unable to open file"<<endl; //Gives that sentence if the file can't be opened
    	for(loop2=0;loop2<=loop;loop2++) //For loop make to cout the lines stored
    		cout<<myobj[loop2]<<endl;    //inside of the variable 'array'
    	return 0;
    error C2679: binary '=' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)

  2. #2
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: c++ help array's and files

    Yes it's possible. Either you write an assignment operator or you write a setter method. In this case an assignment operator will be very confusing since normally that operator is used when you copy objects. A setter method is better i.e. some method that accepts a std::string and copies it to a class internal std::string (or whatever you want to do with it)
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

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