5

別のリクエスト申し訳ありません..現在、トークンを1つずつ読み取っていますが、動作しますが、新しい行があることを知りたい..

私のファイルが含まれている場合

Hey Bob
Now

私に与えるべきです

Hey
Bob
[NEW LINE]
NOW

getline を使用せずにこれを行う方法はありますか?

4

3 に答える 3

16

はい、演算子 >> 文字列で使用する場合は、「空白」で区切られた単語を読み取ります。「空白」には、スペース タブと改行文字が含まれます。

一度に 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";
    }
}
于 2008-11-09T00:16:54.883 に答える
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;
    }
}
于 2008-11-10T04:26:28.920 に答える
1

これは、文字列をトークン化するために私が遭遇したもう 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);
}
于 2009-04-30T11:56:53.503 に答える