別のリクエスト申し訳ありません..現在、トークンを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";
}
小さな追加:
したがって、改行を検出できるようにする必要があります。これは、改行が別のタイプのトークンになることを意味します。したがって、「空白」で区切られた単語をトークンとして、改行を独自のトークンとして持っていると仮定しましょう。
次に、トークン タイプを作成できます。
あとは、トークンのストリーム オペレーターを記述するだけです。
#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);
}