1

我的输入文件是这样的:

C:\Users\DeadCoder\AppData\Local\CoCreate

我正在制作一棵树,我需要在从带有\分隔符的输入文件中读取时抽象目录的名称。和上面的例子一样,我需要分别抽象出c:、users、DeadCoder、Appdata ....希望大家理解问题。现在让我们看看我们得到的选项。

1- istringstream适用于whitespace但不适用于\.

2- strtok()在 char 上工作。所以我必须将我的字符串更改为 char 并且我真的不想这样做。

3- Boost Tokenizer()这个看起来很有趣,我过去对它并不熟悉,只是我刚刚在谷歌上搜索了一下。我复制了代码,它是这样的:

#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
using namespace boost;

int main(){

    string tempStr;
    ifstream fin;
    fin.open("input.txt");
    int i=0;

    while (!fin.eof()){
        getline(fin,tempStr);
        char_separator<char> sep("\"); // error: missing terminating " character
        tokenizer<char_separator<char>> tokens(tempStr, sep);
        for (const auto& t : tokens) {
            cout << t << "." << endl;
        }
}

现在这给出了 "error: boost/foreach.hpp: No such file or directory" 有人可以在这里帮助我的错误。还有其他better way方法可以使用 . 读取输入文件吗\ delimiter?请不要像class tokenizer()我还在学习 c++ 那样使用大量代码。

编辑:我没有安装 boost 库,因此我遇到了这个错误。如果有人可以在tokenize不安装第三个库的情况下解释一种更好的字符串方式,那将是非常受欢迎的。

最好的; 死编码器。

4

3 回答 3

3

在 C++(和其他基于 C 的语言)\中,字符串或字符文字中的字符是转义字符。这意味着它转义了文字中的下一个字符。例如,您可以"在字符串内部拥有一个。要\在字符串文字中包含一个,您需要通过其中两个来转义反斜杠:"\\".

您可以阅读有关 C++ 中有效转义序列的更多信息,例如在此参考中


至于 Boost 的问题,你需要告诉编译器你安装它的位置。这是在 IDE 的项目属性中完成的。


如果您想在使用 Boost 等第三方库的情况下进行标记化,有几种方法。一种方法是使用std::istringstreamand std::getline。另一个使用标准类的findsubstr函数。string

于 2013-02-22T17:07:10.567 回答
2

这里的任何类型的通用标记器都是矫枉过正的。只需使用 std::find( s.begin(), s.end(), '\\' )查找每个分隔符,并使用两个迭代器构造函数std::string将其放入单独的字符串中。(您的编译器将第一个\视为转义字符。)类似于:

std::vector<std::string> fields;
std::string::const_iterator end = s.end();
std::string::const_iterator current = s.begin();
std::string::const_iterator next
        = std::find( current, end, '\\' ):
while ( next != end ) {
    fields.push_back( std::string( current, next ) );
    current = next + 1;
    next = std::find( current, end, '\\' );
}
fields.push_back( std::string( current, next ) );

应该做的伎俩。

于 2013-02-22T17:20:05.417 回答
1
char_separator<char> sep("\") 
                          ^^^ You need to escape the \ . use "\\" 

用于\指示转义序列。但to escape that escape, you need other escape

用这个 :char_separator<char> sep("\\")

安装 boost 库:安装 Boost

其他选择:

getline(fin,tempStr);
char *cstr=new char[tempStr.length()+1];
strcpy(cstr,tempStr.c_str())

//... Now you can use strtok() on cstr
于 2013-02-22T17:07:17.033 回答