2013-11-14 252 views
0

嗨我正在为我的班级工作,并且遇到问题。我想要做的是从文件中获取单词列表,然后将一个随机单词放到一个char数组中,但我不完全确定我应该如何将文本形式的字符串数组转换为字符数组我的代码看起来是这样的目前将字符串数组转换为字符数组

#include <iostream> 
#include <fstream> 
#include <string> 
#include <cstring> 
using namespace std; 

int main(){ 
    ifstream infile; 
    string words[25]; 
    string wordss; 
    char cword[]; 
    int index=0; 
    infile.open("c:\\words.txt) 
    while (infile>>words){ 
     words[index]=words; 
     index=index+1; 



    } 





} 

现在本来我得只是简单地通过随机选择号码进行cword阵列的话阵列的一个随机字状cword =字[0]但没”工作。所以我想知道如何将从字符串数组中选择的单词转换为用于char数组?

+0

'char cword []'对于数组声明是错误的。您必须在声明期间指定尺寸。然后你可以说'cword = words [0] .c_str()''char cword [];''const char * cword' – theAlias

回答

0

应该使用char * cword而不是char cword [],这将允许您在为其分配内存后仅存储一个单词。假设你的单词长度是10,那么你会写为 cword = new char [10];不要忘记删除稍后由delete [] cword分配的内存;

字符串也可以做你正在做的事情,而不用转换成char []。 例如您有: -

string cword = "Hello" 
cout<<cword[2]; // will display l 
cout<<cword[0]; // will display H 

通常的类型转换是通过使用以下的语句2完成。

static_cast<type>(variableName); // For normal variables 
reinterpret_cast<type*>(variableName); // For pointers 

示例代码可以是: -

ifstream infile; 
char words[25][20]; 

int index=0; 
infile.open("c:\\words.txt"); 
while (infile>>words[index]){ 
    cout<<words[index]<<endl; // display complete word 
    cout<<endl<<words[index][2]; // accessing a particular letter in the word 
    index=index+1; 

为了写出好代码,我会建议你坚持只有一个数据类型。对于这个非常项目。