c ++如果我想将ifstream :: get()分成单词,我该怎么办?

时间:2011-05-27 23:22:23

标签: c++ fstream

这是我的代码。我在调用get()的行中不断收到错误。我正在尝试使用分隔符:

char* spamdir = argv[1];

char* hamdir = argv[2];
char* dictname = argv[3];
ofstream* outp = new ofstream;
ifstream* read = new ifstream;
DIR *sdp = opendir(spamdir);
struct dirent *directory;
char* word = (char*)malloc(256);
while(directory = readdir(sdp))
{
    cout << directory->d_name << endl;
    char* name = directory->d_name;
    char* filepath = (char*) malloc(100);
    strcpy(filepath,"\0");
    strcat(filepath,spamdir);
    strcat(filepath,"/");
    strcat(filepath,name);
    read->open(filepath);
    if(read->good())
        cout <<"sweet\n";

    while(read->good())
    {
        read->get(word,255," ");
        cout << word  << endl;
    }
    read->close();
    free(filepath);
}

1 个答案:

答案 0 :(得分:2)

您没有告诉我们错误是什么,但我的猜测是问题是std::istream::get()中的分隔符参数需要是char,但您传递的是字符串。尝试使用' '代替" "

更简单的方法是使用std::getline(),如下所示:

std::string word;
while (std::getline(*read, word, ' ')) {
    std::cout << word << std::endl;
}

每当你在C ++程序中使用malloc时,你可能都在艰难地做事。

(顺便说一句,每当你有编译错误信息时,最好在你的问题中包含这些信息。)