Home > Software design >  Troubles trying to convert string to char[][]
Troubles trying to convert string to char[][]

Time:12-02

I'm building a class named Board, that will get it's details from a txt file.

#define ROW 25;
#define COL 80;
class Board
{
    char _board[ROW][COL] = {0};

public:
    Board(string name); // our new constructor - reads map from file.
};

It receives string name, and tries to open a file with the specific name. In case we are indeed in the right file, I want to read the chars from it, and copy them into a board. I've been trying several things, that are summed up in this code:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
    Board::Board(string name)
{
    string line;
        ifstream file(name);
        int i = 0;
    if (file.is_open())
        {
            while (!file.eof())
            {
    
            (1) getline(file, line);
            (2) const char* test = line.c_str();
            (3) strcpy_s(_board[i], test);

        (4) _board[i] = line;

                    i  ;

            }
// MORE FUNCTIONS NOT RELEVANT TO THIS QUESTION
        }
}

I get the following errors: For (3): The program crashes. For (4): expression must be a modifiable lvalue. For (1), (2): test and line are worked well.

Is there any other simplier way to copy string to char* without using ugly loops, and copy every single char? Why is (3) crashing my program?

Thanks in advance!

CodePudding user response:

Unrelated, but void main() had been deprecated for ages and is incorrect in current versions of the standard: it shall be int main()...

Next while (!file.eof()) is a common but terrible thing: eof becomes true only after a reading operation returned nothing. That means that you will process the last line twice...

For your errors:

  • (4) _board[i] is an array, and an array cannot be on the left size of an assignment (idiomatically: it is not a lvalue)

  • (3): strcpy_s is not a drop-in replacement for strcpy and your compiler should have emit warnings (any correct compiler would have...). It should be:

      strcpy_s(_board[i], COL, test);
    

CodePudding user response:

#include <iostream>
#include <fstream>
#include <string>
#define ROW 25;
#define COL 80;
int i=0;
class Board
{
    char _board[ROW][COL] = {0};

public:
    Board(string name); // our new constructor - reads map from file.
};
Board::Board(string name)
{
   fstream newfile;

   newfile.open(name,ios::in); 

   if (newfile.is_open()){   

      string tp;
      while(getline(newfile, tp)){ 
        strcpy(_board[i], tp);
        i  ;
      }
      newfile.close(); 
   }
}
  • Related