【问题标题】:C++ Reading file TokensC++ 读取文件标记
【发布时间】:2010-09-21 11:31:58
【问题描述】:

另一个请求对不起.. 现在我正在一个一个地读取令牌并且它有效,但是我想知道什么时候有新行..

如果我的文件包含

Hey Bob
Now

应该给我

Hey
Bob
[NEW LINE]
NOW

有没有办法在不使用 getline 的情况下做到这一点?

【问题讨论】:

  • 抱歉,您要做什么?请编辑您的问题以使事情更清楚!
  • 某些编译器无法识别getline。

标签: c++ file token


【解决方案1】:

是的运算符>> 与字符串一起使用时读取“空格”分隔的单词。 “空白”包括空格制表符和换行符。

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

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";
}

小补充:

不使用 getline()

所以你真的希望能够检测到换行符。这意味着换行符成为另一种类型的令牌。所以让我们假设你有用“空格”分隔的单词作为标记,换行符作为它自己的标记。

然后你就可以创建一个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";
    }
}

【讨论】:

    【解决方案2】:

    我不知道你为什么认为std::getline 不好。您仍然可以识别换行符。

    std::string token;
    std::ifstream file("file.txt");
    while(std::getline(file, token)) {
        std::istringstream line(token);
        while(line >> token) {
            std::cout << "Token :" << token << std::endl;
        }
        if(file.unget().get() == '\n') {
            std::cout << "newline found" << std::endl;
        }
    }
    

    【讨论】:

      【解决方案3】:

      这是我遇到的另一种很酷且不那么冗长的字符串标记方式。

      vector<string> vec; //we'll put all of the tokens in here 
      string token;
      istringstream iss("put text here"); 
      
      while ( getline(iss, token, '\n') ) {
             vec.push_back(token);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-09
        • 2013-11-29
        • 1970-01-01
        • 2011-06-29
        • 1970-01-01
        • 2012-02-26
        • 2018-07-01
        • 2020-02-03
        相关资源
        最近更新 更多