質問
別のリクエストで申し訳ありません。 現在、トークンを1つずつ読み取っていますが、動作しますが、新しい行があるかどうかを知りたいです。
ファイルに含まれている場合
Hey Bob
Now
教えてください
Hey
Bob
[NEW LINE]
NOW
getlineを使用せずにこれを行う方法はありますか?
解決
はい演算子>>文字列とともに使用する場合、「空白」で区切られた単語を読み取ります。 「空白」には、空白タブと改行文字が含まれます。
一度に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()を使用せずに
つまり、本当に改行を検出できるようにしたいのです。これは、改行が別のタイプのトークンになることを意味します。したがって、トークンとして「空白」で区切られた単語があり、独自のトークンとして改行があると仮定しましょう。
その後、トークンタイプを作成できます。
あとは、トークンのストリーム演算子を書くだけです:
#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;
}
}
これは、文字列をトークン化するために私が遭遇したもう1つのクールで冗長な方法です。
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);
}
所属していません StackOverflow