另一个请求抱歉..现在我正在逐个阅读令牌并且它有效,但我想知道什么时候有一个新的线路..
如果我的文件包含
Hey Bob
Now
Run Code Online (Sandbox Code Playgroud)
应该给我
Hey
Bob
[NEW LINE]
NOW
Run Code Online (Sandbox Code Playgroud)
有没有办法在不使用getline的情况下执行此操作?
Mar*_*ork 16
是运算符>>当用于字符串时读取'空格'分隔的单词."空白区域"包括空格选项卡和换行符.
如果要一次读取一行,请使用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";
}
Run Code Online (Sandbox Code Playgroud)
小补充:
所以你真的希望能够检测换行.这意味着换行符成为另一种令牌.因此,假设您将单词"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";
}
}
Run Code Online (Sandbox Code Playgroud)