我想读取一个 .txt 文件。
.txt 文件将包含 N 行和 M 列。
txt 文件中的每个词的长度都不同。
示例 txt 文件:
Suppose N = 4 rows
Suppose M = 5 cols
txt 文件的内容:
aa bbb cc dddddddd eeee
aa bbbbbbbbbbbb cc ddddddddddd eeee
aaaaaaaaaa bb cc d e
a b c d eeee
我必须做什么:
我必须将这些字符串存储到一个二维字符串数组中,如下所示:
arr[4][5] =
[aa bbb cc dddddddd eeee]
[aa bbbbbbbbbbbb cc ddddddddddd eeee]
[aaaaaaaaaa bb cc d e ]
[a b c d eeee]
我知道如何创建整数的动态二维数组及其工作正常:
int** arr;
int* temp;
arr = (int**)malloc(row*sizeof(int*));
temp = (int*)malloc(row * col * sizeof(int));
for (int i = 0; i < row; i++)
{
arr[i] = temp + (i * col);
}
int count = 0;
//setting values in 2-D array
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
arr[i][j] = count++;
}
}
但是,当我尝试对字符串做同样的事情时,它崩溃了。
string** arr;
string* temp;
arr = (string**)malloc(row*sizeof(string*));
temp = (string*)malloc(row * col * sizeof(string));
for (int i = 0; i < row; i++)
{
arr[i] = temp + (i * col);
}
//setting values in 2-D array
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
arr[i][j].append("hello"); // CRASH here !!
}
}
如何将每个单词存储在一个数组中??
这是我写的:
#include "stdafx.h"
#include <cstdlib>
#include <iostream>
#include <vector>
#include <map>
#include <fstream>
#include <string>
#include <algorithm>
#include <assert.h> /* assert */
using namespace std;
vector<string> readFile(const string file, int& row, int& col)
{
vector<string> buffer;
ifstream read(file);
string line;
char * writable = NULL;
if (read.is_open())
{
int temp_counter = 0;
while (!read.eof())
{
std::getline(read, line);
writable = new char[line.size() + 1];
std::copy(line.begin(), line.end(), writable);
writable[line.size()] = '\0'; // don't forget the terminating 0
if (temp_counter == 0)//
{
row = std::stoi(line);
++temp_counter;
}
else if (temp_counter == 1)
{
col = std::stoi(line);
++temp_counter;
}
else
{
buffer.push_back(line);
}
}
}
// don't forget to free the string after finished using it
delete[] writable;
return buffer;
}
void create2DDynamicArray(std::vector<string>&v, int row, int col)
{
string** arr;
string* temp;
arr = (string**)malloc(row*sizeof(string*));
temp = (string*)malloc(row * col * sizeof(string));
for (int i = 0; i < row; i++)
{
arr[i] = temp + (i * col);
}
//setting values in 2-D array
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
arr[i][j].append("hello");
}
}
}
int main()
{
vector<string> myvector;
int row=0;
int col=0;
myvector = readFile("D:\\input.txt", row, col);
create2DDynamicArray(myvector, row, col);
getchar();
return 0;
}
txt 文件看起来像:
4
5
aa bbb cc dddddddd eeee
aa bbbbbbbbbbbb cc dddddddddd eeee
aaaaaaaaa bb cc d e
a b c d eeee
最佳答案
不要在 C++ 中使用 malloc
。它不运行字符串的构造函数,因此不为存储在其中的动态字符数组分配空间。请尝试使用 new[]
运算符或智能指针。
string **arr;
arr = new string*[height];
for (int i = 0; i < height; i++)
arr[i] = new string[width];
C++ string
只是动态 char
数组的一种包装器,它必须被初始化(它应该有分配给它的内存)。通过使用 malloc
,您不会调用构造函数,从而导致访问未分配的内存区域。
关于c++ - 如何创建不同大小字符串的动态二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39139130/