运行while循环直到收到特定输入,但如果没有收到c ++则重新运行

时间:2016-12-03 20:12:59

标签: c++ while-loop cin

我正在尝试运行while循环,直到在终端上按下enter,但据我所知,循环在cin.get()处停止,直到收到某些内容。有没有办法让终端输入可选并重新运行while循环? 这是代码中的循环,如果我取出它运行良好的cin.get()部分,我就是无法阻止它。

        while (true) {

        // In each iteration of our main loop, we run the Myo event loop for a set number of milliseconds.
        hub.run(1);

        // Extract first timestamp from Myo (string casted as a number)
        if (tstart == 0){
            stringstream myStream(collector.stampTime);
            myStream >> tstart;
        }

        // Extracting samples from DataCollector
        std::array<float, 3> acceData = collector.acceSamples;
        std::array<float, 3> gyroData = collector.gyroSamples;
        std::array<float, 3> oriData = collector.oriSamples;
        std::array<int8_t, 8> emgData = collector.emgSamples;

        for (int i = 0; i < emgData.size(); i++){

            if (i < 3) {
                // Accelerometer samples
                acce[i] = acceData[i];
                pAcce[i] = acce[i];

                // Gyroscope samples
                gyro[i] = gyroData[i];
                pGyro[i] = gyro[i];

                // Orientation samples
                ori[i] = oriData[i];
                pOri[i] = ori[i];
            }

            // EMG samples
            emg[i] = emgData[i];
            pEMG[i] = emg[i];
        }

        /*
        * Plot the result
        */
        engPutVariable(ep, "Acce", Acce);
        engPutVariable(ep, "Gyro", Gyro);
        engPutVariable(ep, "Ori", Ori);
        engPutVariable(ep, "EMG", EMG);
        engEvalString(ep,"EMG_gather");

        // Extract timestamps from Myo (string casted as a number) and compute elapsed time
        stringstream myStream(collector.stampTime);
        myStream >> tend;
        elapsedTime = (tend - tstart)/1000000;

        // Keep track of how many runs Myo has performed
        x++;
        if (x % 30 == 0){
            std::cout << x << endl;
        }


        if (cin.get() == '\n')
            break;
        else if (cin.get() == '')
            continue;
    }

1 个答案:

答案 0 :(得分:0)

这取决于您希望输入的复杂程度,但根据您发布的内容,您也可以 像这样使用std::signal函数:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

class FixPointNormalize(matplotlib.colors.Normalize):
    """ 
    Inspired by https://stackoverflow.com/questions/20144529/shifted-colorbar-matplotlib
    Subclassing Normalize to obtain a colormap with a fixpoint 
    somewhere in the middle of the colormap.

    This may be useful for a `terrain` map, to set the "sea level" 
    to a color in the blue/turquise range. 
    """
    def __init__(self, vmin=None, vmax=None, sealevel=0, col_val = 0.21875, clip=False):
        # sealevel is the fix point of the colormap (in data units)
        self.sealevel = sealevel
        # col_val is the color value in the range [0,1] that should represent the sealevel.
        self.col_val = col_val
        matplotlib.colors.Normalize.__init__(self, vmin, vmax, clip)

    def __call__(self, value, clip=None):
        x, y = [self.vmin, self.sealevel, self.vmax], [0, self.col_val, 1]
        return np.ma.masked_array(np.interp(value, x, y))

# Combine the lower and upper range of the terrain colormap with a gap in the middle
# to let the coastline appear more prominently.
# inspired by https://stackoverflow.com/questions/31051488/combining-two-matplotlib-colormaps
colors_undersea = plt.cm.terrain(np.linspace(0, 0.17, 56))
colors_land = plt.cm.terrain(np.linspace(0.25, 1, 200))
# combine them and build a new colormap
colors = np.vstack((colors_undersea, colors_land))
cut_terrain_map = matplotlib.colors.LinearSegmentedColormap.from_list('cut_terrain', colors)



# invent some data (height in meters relative to sea level)
data = np.linspace(-1000,2400,15**2).reshape((15,15))


# plot example data
fig, ax = plt.subplots(nrows = 2, ncols=3, figsize=(11,6) )
plt.subplots_adjust(left=0.08, right=0.95, bottom=0.05, top=0.92, hspace = 0.28, wspace = 0.15)

plt.figtext(.5, 0.95, "Using 'terrain' and FixedPointNormalize", ha="center", size=14)
norm = FixPointNormalize(sealevel=0, vmax=3400)
im = ax[0,0].imshow(data+1000, norm=norm, cmap=plt.cm.terrain)
fig.colorbar(im, ax=ax[0,0])

norm2 = FixPointNormalize(sealevel=0, vmax=3400)
im2 = ax[0,1].imshow(data, norm=norm2, cmap=plt.cm.terrain)
fig.colorbar(im2, ax=ax[0,1])

norm3 = FixPointNormalize(sealevel=0, vmax=0)
im3 = ax[0,2].imshow(data-2400.1, norm=norm3, cmap=plt.cm.terrain)
fig.colorbar(im3, ax=ax[0,2])

plt.figtext(.5, 0.46, "Using custom cut map and FixedPointNormalize (adding hard edge between land and sea)", ha="center", size=14)
norm4 = FixPointNormalize(sealevel=0, vmax=3400)
im4 = ax[1,0].imshow(data+1000, norm=norm4, cmap=cut_terrain_map)
fig.colorbar(im4, ax=ax[1,0])

norm5 = FixPointNormalize(sealevel=0, vmax=3400)
im5 = ax[1,1].imshow(data, norm=norm5, cmap=cut_terrain_map)
cbar = fig.colorbar(im5, ax=ax[1,1])

norm6 = FixPointNormalize(sealevel=0, vmax=0)
im6 = ax[1,2].imshow(data-2400.1, norm=norm6, cmap=cut_terrain_map)
fig.colorbar(im6, ax=ax[1,2])

for i, name in enumerate(["land only", "coast line", "sea only"]):
    for j in range(2):
        ax[j,i].text(0.96,0.96,name, ha="right", va="top", transform=ax[j,i].transAxes, color="w" )

plt.show()

这将一直运行直到用户按下#include <iostream> #include <csignal> namespace { volatile std::sig_atomic_t m_stop; } static void app_msg_pump(int sig) { if (sig == SIGINT || sig == SIGTERM) { m_stop = sig; } } int main(int argc, char* argv[]) { m_stop = 0; std::signal(SIGINT, &app_msg_pump); // catch signal interrupt request std::signal(SIGTERM, &app_msg_pump); // catch signal terminate request while (m_stop == 0) { // your loop code here } std::cout << "Stopping.." << std::endl; // your clean up code here return 0; } (通常的控制台信号中断键处理程序),您可以修改上面的代码以忽略按键,并只处理用户请求中断的事实。

希望可以提供帮助。