Пользовательский потоковый манипулятор C++, который изменяет следующий объект в действии

3 вещи:

  • Ваш HTML-код был искажен
  • Вам нужно установить display: none на CSS для того, что вы хотите скрыть в начале
  • [1110 ] Вам нужно вызвать fadeIn (или show) для элемента ПОСЛЕ того, как fadeOut (или hide) завершится, вы можете сделать это с помощью обещаний и функции обратного вызова fadeIn

https: // developer .mozilla.org / en-US / docs / Web / JavaScript / Reference / Global_Objects / Promise http://api.jquery.com/fadein/

var name ;
var nameFormat=true;
function submission() {
    var name = document.getElementById("textbox").value;
    if (name.length > 0) {
        alert("Welcome "+name);
        fadeOutWelcome().then(() => fadeInWelcome());
    }
    else{
        nameFormat==false;
        alert("Please enter the name again");
    }
}

const fadeOutWelcome = () => {
  return new Promise((resolve, reject) => { 
      $("#name").fadeOut(1000, () => resolve());
      $("#welcome").fadeOut(1000);
  });
}

const fadeInWelcome = () => {
  $("#welcome2").fadeIn(1000);
  $("#welcome2-0").fadeIn(1000);
}
#welcome{
    top:30px;
    left: 30px;
    color: antiquewhite;
    border: 2px solid blue;
    background: blue;
    padding: 25px;
  
}

#name{
 
    top:30px;
    left: 500px;
    color: antiquewhite;
    background: blue;
    border: 25px solid blue;
}

body {
    background-color: lightblue;
  }
#welcome2{
  display: none;
    position: relative;
    top:30px;
    left: 30px;
    color: antiquewhite;
    border: 2px solid blue;
    background: blue;
    padding: 25px;
}
HTML




		
		
	Welcome!

	


Welcome to the Myanmar Trivia Quiz
please enter your name and click on "Begin Quiz" to start
Name:

Myanmar Trivia Quiz
Test your Demographic Knowledge
--------------------------------------------------------------------------------------

57
задан Kara 6 August 2015 в 21:55
поделиться

7 ответов

Во-первых, вам нужно сохранить некоторое состояние в каждом поток. Вы можете сделать это с помощью функции iword и индекса, который вы передаете ей, заданного xalloc :

inline int geti() { 
    static int i = ios_base::xalloc();
    return i;
}

ostream& add_one(ostream& os) { os.iword(geti()) = 1; return os; } 
ostream& add_none(ostream& os) { os.iword(geti()) = 0; return os; }

Имея это на своем месте, вы уже можете получить некоторое состояние во всех потоках. Сейчас, вам просто нужно подключиться к соответствующей операции вывода. Числовой вывод выполняется аспектом, потому что он потенциально зависит от локали. Таким образом, вы можете сделать

struct my_num_put : num_put<char> {
    iter_type 
    do_put(iter_type s, ios_base& f, char_type fill, long v) const { 
        return num_put<char>::do_put(s, f, fill, v + f.iword(geti())); 
    } 

    iter_type 
    do_put(iter_type s, ios_base& f, char_type fill, unsigned long v) const { 
        return num_put<char>::do_put(s, f, fill, v + f.iword(geti())); 
    } 
}; 

Теперь вы можете проверить материал.

int main() {
    // outputs: 11121011
    cout.imbue(locale(locale(),new my_num_put));
    cout << add_one << 10 << 11 
         << add_none << 10 << 11;
}

Если вы хотите, чтобы увеличивалось только следующее число, просто установите слово на 0 снова после каждого вызова do_put .

72
ответ дан 24 November 2019 в 19:39
поделиться

Я полностью согласен с Нилом Баттервортом в этом вопросе, однако в конкретном случае, который вы используете, вы можете сделать это полностью ужасный хак Не делайте этого в любом производственном коде. В нем много ошибок. Во-первых, он работает только в вашей строчке выше, он не меняет состояние основного потока.

class plusone_stream : public std::ostream
{
  public:
    std::ostream operator<<(int i)
    {
      _out << i+1;
      return *this;
    }
};

std::ostream& plusone(std::ostream& out)
{
    return plusone_stream(out);
}
13
ответ дан 24 November 2019 в 19:39
поделиться

Я создал простое решение для вашего теста без использования . Я не могу обещать, что такой же подход будет работать в реальной жизни.

Основной подход заключается в том, что cout << plusone возвращает временный вспомогательный объект ( PlusOnePlus ), который в поворот имеет перегруженный оператор << , который выполняет сложение.

Я протестировал его в Windows:

PlusOne plusone;
cout << plusone << 41

выдает «42», как и ожидалось. Вот код:

class PlusOnePlus {
public:
    PlusOnePlus(ostream& os) : m_os(os) {}
    // NOTE: This implementation relies on the default copy ctor,
    // assignment, etc.
private:
    friend ostream& operator << (PlusOnePlus& p, int n);
    ostream& m_os;
};

class PlusOne {
public:
    static void test(ostream& os);
};

PlusOnePlus operator << (ostream& os, const PlusOne p)
{
    return PlusOnePlus(os);
}

ostream& operator << (PlusOnePlus& p, int n)
{
    return p.m_os << n + 1;
}

void PlusOne::test(ostream& os)
{
    PlusOne plusone;
    os << plusone << 0 << endl;
    os << plusone << 41 << endl;
}

РЕДАКТИРОВАТЬ: прокомментировал код, чтобы указать, что я полагаюсь на конструктор копирования по умолчанию (и т. Д.) Для PlusOnePlus . Надежная реализация, вероятно, определит их

2
ответ дан 24 November 2019 в 19:39
поделиться

Вам придется играть с потоковыми состояниями. Я добавил в закладки следующие ссылки на эту тему:

Поскольку библиотека Мачея Собчака больше не доступна в Интернете, и поскольку лицензия позволяет мне делать это Итак, (поправьте меня, если я ошибаюсь), вот копия его основного файла, который мне удалось спасти из забвения:

// streamstate.h
//
// Copyright (C) Maciej Sobczak, 2002, 2003
//
// Permission to copy, use, modify, sell and distribute this software is
// granted provided this copyright notice appears in all copies.  This software
// is provided "as is" without express or implied warranty, and with no claim
// as to its suitability for any purpose.
//
// <http://lists.boost.org/Archives/boost/2002/10/38275.php>
// <http://www.ddj.com/dept/cpp/184402062?pgno=1>
// <http://www.msobczak.com/prog/publications.html>

#ifndef STREAMSTATE_H_INCLUDED
#define STREAMSTATE_H_INCLUDED

#include <ios>
#include <istream>
#include <ostream>

// helper exception class, thrown when the source of error
// was in one of the functions managing the additional state storage
class StreamStateException : public std::ios_base::failure
{
public:
    explicit StreamStateException()
        : std::ios_base::failure(
            "Error while managing additional IOStream state.")
    {
    }
};

// State should be:
// default-constructible
// copy-constructible
// assignable

// note: the "void *" slot is used for storing the actual value
//       the "long" slot is used to propagate the error flag
template
<
    class State,
    class charT = char,
    class traits = std::char_traits<charT>
>
class streamstate
{
public:
    // construct with the default state value
    streamstate() {}

    // construct with the given stream value
    streamstate(const State &s) : state_(s) {}

    // modifies the stream
    std::basic_ios<charT, traits> &
    modify(std::basic_ios<charT, traits> &ios) const
    {
        long *errslot;
        void *&p = state_slot(ios, errslot);

        // propagate the error flag to the real stream state
        if (*errslot == std::ios_base::badbit)
        {
            ios.setstate(std::ios_base::badbit);
            *errslot = 0;
        }

        // here, do-nothing-in-case-of-error semantics
        if (ios.bad())
            return ios;

        if (p == NULL)
        {
            // copy existing state object if this is new slot
            p = new State(state_);
            ios.register_callback(state_callback, 0);
        }
        else
            *static_cast<State*>(p) = state_;

        return ios;
    }

    // gets the current (possibly default) state from the slot
    static State & get(std::basic_ios<charT, traits> &ios)
    {
        long *errslot;
        void *&p = state_slot(ios, errslot);

        // propagate the error flag to the real stream state
        if (*errslot == std::ios_base::badbit)
        {
            ios.setstate(std::ios_base::badbit);
            *errslot = 0;
        }

        // this function returns a reference and therefore
        // the only sensible error reporting is via exception
        if (ios.bad())
            throw StreamStateException();

        if (p == NULL)
        {
            // create default state if this is new slot
            p = new State;
            ios.register_callback(state_callback, 0);
        }

        return *static_cast<State*>(p);
    }

private:
    // manages the destruction and format copying
    // (in the latter case performs deep copy of the state)
    static void state_callback(std::ios_base::event e,
        std::ios_base &ios, int)
    {
        long *errslot;
        if (e == std::ios_base::erase_event)
        {
            // safe delete if state_slot fails
            delete static_cast<State*>(state_slot(ios, errslot));
        }
        else if (e == std::ios_base::copyfmt_event)
        {
            void *& p = state_slot(ios, errslot);
            State *old = static_cast<State*>(p);

            // Standard forbids any exceptions from callbacks
            try
            {
                // in-place deep copy
                p = new State(*old);
    }
            catch (...)
            {
                // clean the value slot and
                // set the error flag in the error slot
                p = NULL;
                *errslot = std::ios_base::badbit;
            }
        }
    }

    // returns the references to associated slot
    static void *& state_slot(std::ios_base &ios, long *&errslot)
    {
        static int index = std::ios_base::xalloc();
        void *&p = ios.pword(index);
        errslot = &(ios.iword(index));

        // note: if pword failed,
        // then p is a valid void *& initialized to 0
        // (27.4.2.5/5)

        return p;
    }

    State state_;
};

// partial specialization for iword functionality
template
<
    class charT,
    class traits
>
class streamstate<long, charT, traits>
{
public:
    // construct with the default state value
    streamstate() {}

    // construct with the given stream value
    streamstate(long s) : state_(s) {}

    // modifies the stream
    // the return value is not really useful,
    // it has to be downcasted to the expected stream type
    std::basic_ios<charT, traits> &
    modify(std::basic_ios<charT, traits> &ios) const
    {
        long &s = state_slot(ios);
        s = state_;

        return ios;
    }

    static long & get(std::basic_ios<charT, traits> &ios)
    {
        return state_slot(ios);
    }

private:
    static long & state_slot(std::basic_ios<charT, traits> &ios)
    {
        static int index = std::ios_base::xalloc();
        long &s = ios.iword(index);

        // this function returns a reference and we decide
        // to report errors via exceptions
        if (ios.bad())
            throw StreamStateException();

        return s;
    }

    long state_;
};

// convenience inserter for ostream classes
template
<
    class State,
    class charT,
    class traits
>
std::basic_ostream<charT, traits> &
operator<<(std::basic_ostream<charT, traits> &os,
    const streamstate<State> &s)
{
    s.modify(os);
    return os;
}

// convenience extractor for istream classes
template
<
    class State,
    class charT,
    class traits
>
std::basic_istream<charT, traits> &
operator>>(std::basic_istream<charT, traits> &is,
    const streamstate<State> &s)
{
    s.modify(is);
    return is;
}

// the alternative if there is a need to have
// many different state values of the same type
// here, the instance of streamstate_value encapsulates
// the access information (the slot index)

template
<
    class State,
    class charT = char,
    class traits = std::char_traits<char>
>
class streamstate_value
{
public:

    streamstate_value()
        : index_(-1)
    {
    }

    // returns a reference to current (possibly default) state
    State & get(std::basic_ios<charT, traits> &ios)
    {
        long *errslot;
        void *&p = state_slot(ios, errslot, index_);

        // propagate the error flag to the real stream state
        if (*errslot == std::ios_base::badbit)
        {
            ios.setstate(std::ios_base::badbit);
            *errslot = 0;
        }

        // this function returns a reference and the only
        // sensible way of error reporting is via exception
        if (ios.bad())
            throw StreamStateException();

        if (p == NULL)
        {
            // create default state if this is new slot
            p = new State;
            ios.register_callback(state_callback, index_);
        }

        return *static_cast<State*>(p);
    }

private:

    // manages the destruction and format copying
    // (in the latter case performs deep copy of the state)
    static void state_callback(std::ios_base::event e,
        std::ios_base &ios, int index)
    {
        long *errslot;
        if (e == std::ios_base::erase_event)
        {
            // safe delete if state_slot fails
            delete static_cast<State*>(state_slot(ios, errslot, index));
        }
        else if (e == std::ios_base::copyfmt_event)
        {
            void *& p = state_slot(ios, errslot, index);
            State *old = static_cast<State*>(p);

            // Standard forbids any exceptions from callbacks
            try
            {
                // in-place deep copy
                p = new State(*old);
    }
            catch (...)
            {
                // clean the value slot and set the error flag
                // in the error slot
                p = NULL;
                *errslot = std::ios_base::badbit;
            }
        }
    }

    // returns the references to associated slot
    static void *& state_slot(std::ios_base &ios,
        long *& errslot, int & index)
    {
        if (index < 0)
        {
            // first index usage
            index = std::ios_base::xalloc();
        }

        void *&p = ios.pword(index);
        errslot = &(ios.iword(index));

        // note: if pword failed,
        // then p is a valid void *& initialized to 0
        // (27.4.2.5/5)

        return p;
    }

    int index_;
};

// partial specialization for iword functionality
template
<
    class charT,
    class traits
>
class streamstate_value<long, charT, traits>
{
public:
    // construct with the default state value
    streamstate_value()
        : index_(-1)
    {
    }

    long & get(std::basic_ios<charT, traits> &ios)
    {
        if (index_ < 0)
        {
            // first index usage
            index_ = std::ios_base::xalloc();
        }

        long &s = ios.iword(index_);
        if (ios.bad())
            throw StreamStateException();

        return s;
    }

private:
    long index_;
};

#endif // STREAMSTATE_H_INCLUDED 
1
ответ дан 24 November 2019 в 19:39
поделиться

Манипуляторы hex , dec и oct просто изменяют свойство basefield существующего stream .

См. C ++ Reference для более подробной информации об этих манипуляторах.

Как написано в Ответ Нила Баттерворта , вам необходимо расширить существующий поток. классы или создайте свой собственный, чтобы иметь манипуляторы, которые влияют на будущие значения, вставленные в поток.

В примере вашего манипулятора plusone объект потока должен иметь внутренний флаг, чтобы указывать этот должен быть добавлен ко всем вставленным значениям. Манипулятор plusone просто установит этот флаг, а код для обработки вставки потока проверит этот флаг перед вставкой чисел.

-1
ответ дан 24 November 2019 в 19:39
поделиться

It's not a direct answer to your question, but don't you think that using a plain old function is both simpler to implement and clearer to use than writing a full blown manipulator?

#include <sstream>

template<typename T>
std::string plusone(T const& t) {
    std::ostringstream oss;
    oss << (t + 1);
    return oss.str();
}

Usage:

cout << plusone(42);

By "clear to use", I mean that the user doesn't need to ask themselves, "Does it affect only the next item, or all subsequent items?" It's obvious from inspection that only the argument of the function is affected.

(For the plusone() example, you could simplify even further by just returning a T instead, but returning a std::string serves the general case.)

2
ответ дан 24 November 2019 в 19:39
поделиться

Подход Литба - «правильный путь» и необходим для сложных вещей, но что-то подобное может быть достаточно хорошим. Добавьте конфиденциальность и дружбу по вкусу.

struct PlusOne
{
   PlusOne(int i) : i_(i) { }
   int i_;
};

std::ostream &
operator<<(std::ostream &o, const PlusOne &po)
{
   return o << (po.i_ + 1);
}

std::cout << "1 + 1 = " << PlusOne(num2); // => "1 + 1 = 2"

В этом простом примере создание и потоковая передача временного объекта не кажется намного более полезным, чем определение функции plusOne (), как кто-то уже предложил. Но предположим, что вы хотели, чтобы это работало так:

std::ostream &
operator<<(std::ostream &o, const PlusOne &po)
{
   return o << po.i_ << " + 1 = " << (po.i_ + 1);
}

std::cout << PlusOne(num2); // => "1 + 1 = 2"
0
ответ дан 24 November 2019 в 19:39
поделиться
Другие вопросы по тегам:

Похожие вопросы: