【发布时间】:2016-08-25 07:26:03
【问题描述】:
我想读取一个 .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
aaaaaaaaaa bb cc d e
a b c d eeee
【问题讨论】:
-
您将 int 更改为 char。您为字符串分配空间,而不是为 int。
-
添加为每个字符串的空字符分配一个额外的条目。
-
为什么不选择一个 C和C++?如果你打算使用 C,他们会说you shouldn't cast the result of
malloc()in C。如果你打算使用 C++,为什么不使用new[]而不是malloc()? -
“但是,当我尝试对字符串做同样的事情时,它会崩溃。”如何?为什么不发布Minimal, Complete, and Verifiable example?
-
如果你打算使用 C++,为什么还要关心这样的分配。