如何指定从C ++中的文件开始读取特定数量的单词?

时间:2013-08-01 10:17:13

标签: c++ file-io

我试图从文件中特定地读取一定数量的单词 我写了这个,但似乎我做得不好!我很高兴知道是否有更好的方法。 这是我的代码:

FILE* filePointer;
wstring inputString = L"";
wstring wstr = L"";

int position = 0;

_wfopen_s(&filePointer, fileToReadFrom, L"r");
_setmode(_fileno(filePointer), _O_U8TEXT);

wifstream file(filePointer);

getline(file, inputString);
while (inputString[position] != L' ')
{
    position++;
}
fseek(filePointer, position, SEEK_SET);//start reading after first word

while (file.good())
{
     getline(file, inputString);

     for (wsregex_iterator it(inputString.begin(), inputString.end(), biRegx), it_end; it != it_end; ++it)
     {
         //Filling the bigram container
         wstr = (wstring) (*it)[0];
         bigramStatMap[wstr]++;

     }
}

2 个答案:

答案 0 :(得分:3)

使用for循环,读取您需要的单词数:

unsigned int words_before_begin;
std::string sux_string;
std::ifstream file_stream("Your file");

for(unsigned int i = 0 ; i < words_before_begin ; ++i)
    file_stream >> aux_string; //istream reads strings word by word, using spaces as separators.

/* Your reading code starts here */

答案 1 :(得分:1)

复制整个载体

std::ifstream stream ("file_name");

std::vector<std::string> words;

    std::copy(std::istream_iterator<std::string>(stream),
                  std::istream_iterator<std::string>(),
                  std::back_inserter(words)
                 );

开始从words[position+1]

进行访问