本文介绍了C ++读取文件令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,另一个请求。.
现在我正在逐个读取令牌,它可以工作,但是我想知道何时有新行。.

another request sorry..Right now I am reading the tokens in one by one and it works, but I want to know when there is a new line..

如果我的文件包含

Hey Bob
Now

应该给我

Hey
Bob
[NEW LINE]
NOW

有没有办法

推荐答案

是的,运算符>>与字符串一起使用时,用'空白'分隔的单词。 空白包含空格标签和换行符。

Yes the operator>> when used with string read 'white space' separated words. A 'White space' includes space tab and new line characters.

如果您想一次读取一行,请使用std :: getline()
$ b然后可以使用字符串流分别标记该行。

If you want to read a line at a time use std::getline()
The line can then be tokenized separately with a string stream.

std::string   line;
while(std::getline(std::cin,line))
{

    // If you then want to tokenize the line use a string stream:

    std::stringstream lineStream(line);
    std::string token;
    while(lineStream >> token)
    {
        std::cout << "Token(" << token << ")\n";
    }

    std::cout << "New Line Detected\n";
}

小添加:

因此,您真的希望能够检测到换行符。这意味着换行符成为另一种令牌。因此,假设您有用空白分隔的单词作为标记,而换行符作为其自己的标记。

So you really want to be able to detect a newline. This means that newline becomes another type of token. So lets assume that you have words separated by 'white spaces' as tokens and newline as its own token.

然后您可以创建标记类型。

然后,您所要做的就是为令牌编写流运算符:

Then you can create a Token type.
Then all you have to do is write the stream operators for a token:

#include <iostream>
#include <fstream>

class Token
{
    private:
        friend std::ostream& operator<<(std::ostream&,Token const&);
        friend std::istream& operator>>(std::istream&,Token&);
        std::string     value;
};
std::istream& operator>>(std::istream& str,Token& data)
{
    // Check to make sure the stream is OK.
    if (!str)
    {   return str;
    }

    char    x;
    // Drop leading space
    do
    {
        x = str.get();
    }
    while(str && isspace(x) && (x != '\n'));

    // If the stream is done. exit now.
    if (!str)
    {
        return str;
    }

    // We have skipped all white space up to the
    // start of the first token. We can now modify data.
    data.value  ="";

    // If the token is a '\n' We are finished.
    if (x == '\n')
    {   data.value  = "\n";
        return str;
    }

    // Otherwise read the next token in.
    str.unget();
    str >> data.value;

    return str;
}
std::ostream& operator<<(std::ostream& str,Token const& data)
{
    return str << data.value;
}


int main()
{
    std::ifstream   f("PLOP");
    Token   x;

    while(f >> x)
    {
        std::cout << "Token(" << x << ")\n";
    }
}

这篇关于C ++读取文件令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 05:43