将字符串数组中的单词转换为char数组

时间:2013-11-14 15:54:23

标签: arrays string visual-c++ char type-conversion

您好,我正在为我的班级开设一个刽子手项目,而且我遇到了一个问题。我想要做的是从文件中获取一个单词列表,然后将一个随机单词放入一个char数组中,但我不确定我应该如何将字符串数组转换为字符串数组到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 = words [0])将cword数组变为一个随机单词,而不是单词数组,但这并不起作用。所以我想知道如何转换从字符串数组中选择的单词用于char数组?

1 个答案:

答案 0 :(得分:0)

应使用char * cword而不是char cword [],这将允许您在为其分配内存后仅存储单个单词。让我们说你的单词长度是10然后你会写为 cword = new char [10];不要忘记删除以后通过delete [] cword;

分配的内存

String也可以执行您尝试执行的操作,而无需转换为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;

为了编写一个好的代码,我建议你只坚持一种数据类型。对于这个项目。