0
我需要製作二維數組,但問題是我需要使用字符串大小作爲數組的大小。到目前爲止,我做到了這一點,但我不斷收到錯誤「表達式必須有一個常數值」。我的程序需要從txt文件讀取一個字符串,然後使用字符串長度/大小來表示二維數組大小。例如:我在txt文件中寫了「hello」,其長度是5.現在我需要使用這個長度並將其存儲爲變量N,並將其用作二維數組的維數。 如何爲這個例子做傢伙?如何將非consant值分配給C++中的二維數組大小?
int main()
{
string s;
ifstream myfile("palindrome.txt", ios::out); //reading my txt file
if (myfile.is_open())
{
getline(myfile, s); //storing string in variable s
}
myfile.close();
int l = s.size(); //reading size of string and storing to variable l
const int N = l;
int* R= new int[2][N + 1];
什麼是錯誤信息? – Phorce
錯誤\t C2540 \t與數組綁定的非常量表達式 – darius
如果要爲具有一個新數組的數組分配內存,則第二個大小必須是常量。在你的情況下,我認爲你應該聲明一個數組(或向量)的字符串。 –