我想讀取.txt文件。如何創建不同大小字符串的動態二維數組
.txt文件將包含N行和M列。
txt文件中的每個單詞將具有不同的長度。
樣品txt文件:txt文件的
Suppose N = 4 rows
Suppose M = 5 cols
內容:
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文件的樣子:
AA BBB CC DDDDDDDD EEEE
AA bbbbbbbbbbbb CC ddddddddddd eeee
AAAAAAAAAA BB CC dË
A B C d EEEE
你改變INT爲char。您爲字符串分配空間,而不是爲int分配空間。 – Mirakurun
添加爲每個字符串的空字符分配一個額外的條目。 –
爲什麼不選擇* C和C++之一?如果你打算使用C,他們會說[你不應該在C]中拋出'malloc()'的結果(http://stackoverflow.com/questions/605845/do-i-cast-the-result-的-的malloc)。如果你打算使用C++,爲什麼不使用'new []'而不是'malloc()'? – MikeCAT