2017-01-22 181 views
-5

首先,我想說我是初學者。對不起,我愚蠢的問題。無法將字符串轉換爲常量字符/字符串*爲int *

我的程序應該要求輸入的單詞數量。具體說這個標籤長度是指向單詞標籤的指針長度標籤(可能聽起來令人困惑,但英語不是我的第一語言,我的道歉,我也不明白指針)。

單詞選項卡也應該有每個單詞的確切長度,因此strlen。我究竟做錯了什麼?

int il,len; 
string x; 
cout<<"Amount of words: "; 
cin>>il; 
int **t; 
t=new int*[il]; 
for(int i=0; i<il; i++) 
{ 
    cout<<"Word: "; 
    cin>>x; 
    len=strlen(x); 
    t[i]=new string[len]; 
    cout<<endl; 
} 
cout<<"You wrote:"<<endl; 
for(int i=0; i<il; i++) 
{ 
    cout<<t[i]; 
    delete [] t[i]; 
} 
delete[] t; 
+0

'strlen'並不需要一個類的字符串對象,但一個const指向字符串'字符*' – Raindrop7

+0

什麼是標籤?你的意思是數組(如表中所示)? –

+3

't'的類型爲'int **','t [i]'的類型爲'int *'。你不能把'std :: string *'對象賦給'int *'。再加上你的代碼中的一些其他錯誤;您可能想要瀏覽一些[resources](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)來幫助您理解C++類型系統,這比我們可以在這裏解釋的更廣泛 – WhiZTiM

回答

1

strlen()不採取類string對象,而是需要一個指向字符串char*

len = strlen(x); // error so correct it to: 
len = x.length(); 

也可以不是指針初始化爲整數類字符串:

int **t; 
t[i]=new string[len]; 
  • 你真的想要一個arr字符串的y但代碼確實是一個爛攤子,所以如果你想要這個如何:

    int il; 
    
    cout << "Amount of words: "; 
    cin >> il; 
    
    string *t; 
    t = new string[il]; 
    
    for(int i = 0; i < il; i++) 
    { 
        cout << "Word: "; 
        cin >> t[i]; // there's no need for a temporary string `x`; you can directly input the elements inside the loop 
        cout << endl; 
    } 
    
    cout << "You wrote: " << endl; 
    
    for(int i = 0; i < il; i++) 
        cout << t[i] << endl; 
    
    delete[] t; 
    
+0

讓我們坦率地說。代碼是一團糟。它應該傾倒並重新開始 –

+1

@EdHeal:是的,你是真的!因此我建議他/她的代碼 – Raindrop7

+1

'std :: vector '可能是一種改進。 – YSC