【发布时间】:2015-11-17 14:28:08
【问题描述】:
我知道最终我需要将一个空格包含 3 个字符的三元组从前一个字符串更改为一个动态数组来解决这个问题,但我一开始尝试将我的数组的容量设置得足够大。但是,当我编译我的代码时,就会出现错误。
#error: variable length array of non-POD element type 'string' (aka 'basic_string<char>'#
代码:
//global variable
int CAPACITY = 1000;
int main()
{
//a string that reads in the language of the text
string language = "";
//a string that reads in the file name of the text
string filename = "text.txt";
//a string that reads in the original text characters
string original = "";
//a string that reads in the modified original array
string rid_of_spaces = "";
//an array with capacity that stores the trigrams
string trigrams[CAPACITY];
ifstream finput;
char c;
//the length of an array
int sLength = 0;
//the tracker for trigrams
int counter = 0;
cin >> language >> filename;
finput.open(filename.c_str());
while (finput.get(c)){
//to test if the character is alpha
if (isalpha(c)){
//change the alphabet to lowercase
c = tolower(c);
//store the modified letter in the array
original += c;
}
//change any other characters into a space
else original += ' ';
}
sLength = original.length();
//loop through the original array and change mutiple spaces into one
for (int i = 0; i < sLength; i++){
if (isalpha(original[i]))
rid_of_spaces += original[i];
else {
while (original[i] == ' ')
i++;
rid_of_spaces += ' ';
rid_of_spaces += original[i];
}
}
sLength = rid_of_spaces.length();
for (int i = 0; i < CAPACITY; i++)
trigrams[i] = 0;//initialize each element to 0
for (int i = 0; i < sLength - 2; i++){
trigrams[counter] += rid_of_spaces[i]
+ rid_of_spaces[i + 1]
+ rid_of_spaces[i + 2];
counter++;
}
cout << filename << endl;
cout << original << endl;
cout << rid_of_spaces << endl;
for (int i = 0; i < counter; i++)
cout << trigrams[i] << endl;
finput.close();
return 0;
}
【问题讨论】:
-
用
std::vector代替动态数组怎么样? -
试试
const int CAPACITY -
@MikeCAT 对不起,但不知道那是什么
-
std::vector是 C++ 标准模板库之一,它提供了变长数组。 -
@MikeCAT 哦,谢谢 :)
标签: c++ arrays string compiler-errors dynamic-arrays