2017-01-22 184 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