简体   繁体   中英

Putting an std::string into a char[][] array

So I'm attempting to create a Befunge interperter and reading a text file into an array. I'm using this code:

char map[100][100]; //not 85 x 20
//load the source
ifstream f;
f.open("file.txt", ios::in);
string s;
int i = 0;
while(f.good() && i < 100)
{
    getline(f, s);
    map[i] = s.c_str();
    i++;
}

This doesn't work, does anyone know a way to do it without manually looping through the string?

Use strncpy() and specify the number of bytes:

strncpy(map[i], s.c_str(), 100);
map[i][99] = '\0'; /* this could trim s.c_str(), but at least you don't get an overflow */

instead of:

map[i] = s.c_str();

By specifying the number of bytes copied as, at most, 100 , you ensure that you don't overflow map[i] . The strncpy() function will pad map[i] with terminators, if strlen(s.c_str()) < 100 . In the case where strlen(s.c_str()) >= 100 , the string will be truncated in order to provide map[i] with the requisite null terminator.

I think it is safer to do so

char* map[100];
....   

while(f.good() && i < 100)
{
    getline(f, s);
    map[i] = new char[s.length() + 1];
    strcpy (map[i], s.c_str());
    i++;
}

Contrary to the other answers already posted in here, you should NOT be attempting to use strcpy to copy into "map". Before you do any copying, you want to ensure that you do not overrun the buffer. To do this, you should not use the size of the source, but instead the size of the destination. The reason for this is that the source could potentially be longer than the destination has room. In order to avoid an issue that might not rear its head until you've done some other intensive computations you should ensure that you don't attempt to copy into a destination that isn't large enough to contain what you are trying to copy into it.

This is the function signature for copying strings (well, the one you should be using here):

strncpy(dest, source, size);

Here's what you should use instead:

strncpy(map[i], s.c_str(), sizeof(map[i]));

Edit:

Alternatively you could use strncpy_s() (if you are on Windows!), which allows you to specify both source and destination lengths.

strncpy_s(dest, dest_size, source, source_size)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM