在我的C++代码中,我希望从文本文件(*.txt)中读取并标记每个条目。更具体地说,我希望能够从文件中读取单个单词,如“格式”、“堆栈”、“杰森”、“欧洲”等。
我选择使用fstream来执行此任务,并且不知道如何将它的分隔符设置为我想要使用的分隔符(空格、\n以及连字符甚至撇号,如“Mcdonal‘s”中的)。我认为空格和\n是默认的分隔符,但连字符不是,但我希望将它们作为分隔符来处理,以便在解析文件时,我将得到"blah blah动物-cat“中的单词"blah”、"blah“、" xxx”、“动物”、"cat“。
也就是说,我希望能够从“堆栈溢出”、“you‘s”等获得两个字符串,并且仍然能够同时保持\n和空格作为分隔符。
发布于 2012-04-29 22:10:01
istream将“空白”视为分隔符。它使用区域设置来告诉它哪些字符是空白。区域设置又包括一个分类字符类型的类型facet。这样一个方面看起来可能是这样的:
#include <locale>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <sstream>
class my_ctype : public
std::ctype<char>
{
mask my_table[table_size];
public:
my_ctype(size_t refs = 0)
: std::ctype<char>(&my_table[0], false, refs)
{
std::copy_n(classic_table(), table_size, my_table);
my_table['-'] = (mask)space;
my_table['\''] = (mask)space;
}
};还有一个小测试程序来证明它是有效的:
int main() {
std::istringstream input("This is some input from McDonald's and Burger-King.");
std::locale x(std::locale::classic(), new my_ctype);
input.imbue(x);
std::copy(std::istream_iterator<std::string>(input),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}结果:
This
is
some
input
from
McDonald
s
and
Burger
King.istream_iterator<string>使用>>从流中读取单个字符串,因此如果直接使用它们,则应该得到相同的结果。您需要包含的部分是创建区域设置并使用imbue使流使用该区域设置。
发布于 2012-04-29 21:48:57
您可以使用
istream::getline(char* buffer, steamsize maxchars, char delim)虽然这只支持一个分隔符。要进一步拆分不同分隔符上的行,可以使用
char* strtok(char* inString, const char* delims) 需要多个测定仪。当您使用strtok时,您只需要第一次传递缓冲区的地址--在此之后,只需传入一个null,它就会给出它给您的下一个令牌,在没有更多的时候返回一个空指针。
编辑:一个特定的实现应该类似于
char buffer[120]; //this size is dependent on what you expect the file to contain
while (!myIstream.eofbit) //I may have forgotten the exact syntax of the end bit
{
myIstream.getline(buffer, 120); //using default delimiter of \n
char* tokBuffer;
tokBuffer = strtok(buffer, "'- ");
while (tokBuffer != null) {
cout << "token is: " << tokBuffer << "\n";
tokBuffer = strtok(null, "'- "); //I don't need to pass in the buffer again because it remembers the first time I called it
}
}https://stackoverflow.com/questions/10376199
复制相似问题