另一个请求抱歉.. 现在我一个接一个地阅读令牌并且它有效,但我想知道什么时候有一个新线..

如果我的文件包含

Hey Bob
Now

应该给我

Hey
Bob
[NEW LINE]
NOW

有没有办法在不使用getline的情况下执行此操作?

有帮助吗?

解决方案

是运营商>>当用字符串读'空格'分隔的单词时。 “空白区域”包括空格标签和换行符。

如果你想一次读一行,请使用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()

所以你真的希望能够检测换行。这意味着换行符成为另一种令牌。因此,假设您将单词“white spaces”分隔为标记,将换行符作为自己的标记。

然后您可以创建令牌类型。
然后,您所要做的就是为令牌编写流操作符:

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

其他提示

我不知道为什么你认为 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;
    }
}

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

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);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top