如何将 std::chrono 转换为 int

How do I convert std::chrono to int

我一直在尝试制作一个 wpm 计数器,长话短说,我 运行 遇到了一个问题: 使用高分辨率时钟后,我需要将其除以12,但无法将std::chrono转换为int。这是我的代码:

#include <iostream>
#include <chrono>
#include <Windows.h>
#include <synchapi.h>

using namespace std;
using namespace std::chrono;
int main()
{
    typedef std::chrono::high_resolution_clock Time;
    typedef std::chrono::seconds s;

    string text;
    string ctext = "One two three four five six seven eight nine ten eleven twelve";

    cout << "Type: "<< ctext << " in" << "\n" << "5" << endl;
    Sleep(1000);
    cout << "4" << endl;
    Sleep(1000);
    cout << "3" << endl;
    Sleep(1000);
    cout << "2" << endl;
    Sleep(1000);
    cout << "1" << endl;
    Sleep(1000);
    cout << "GO" << endl;

    auto start = Time::now();
    cin >> text;
    auto stop = Time::now();

    float wpm = stop - start / 12;
    
    if (ctext == text)
    {
        cout << "Correct! WPM: " << wpm;
    }
    else
    {
        cout << "You had some errors. Your WPM: " << wpm;
    }
}

除了使用 std::chrono 之外,还有什么替代方法可以使用吗?

std::chrono 将通过一些小改动优雅地解决这个问题...

  • 而不是 Sleep(1000);,更喜欢 this_thread::sleep_for(1s);。你需要 header <thread> 而不是 <Windows.h><synchapi.h>.

  • cin >> text; 只会读一个字。要阅读你想要的整行 getline(cin, text);.

  • 首先计算以浮点类型存储的每个单词的分钟数是最简单的。要获得总浮点分钟数,您只需将持续时间除以 1.0min。这导致 long double。然后将总分钟数除以 12 得到每个单词的分钟数:

.

auto mpw = (stop - start) / 1.0min / 12;
  • 然后只需反转 mpw 即可得到每分钟的字数:

.

float wpm = 1/mpw;

总结:

#include <chrono>
#include <iostream>
#include <thread>

using namespace std;
using namespace std::chrono;

int main()
{
    typedef steady_clock Time;
    typedef seconds s;

    string text;
    string ctext = "One two three four five six seven eight nine ten eleven twelve";

    cout << "Type: "<< ctext << " in" << "\n" << "5" << endl;
    this_thread::sleep_for(1s);
    cout << "4" << endl;
    this_thread::sleep_for(1s);
    cout << "3" << endl;
    this_thread::sleep_for(1s);
    cout << "2" << endl;
    this_thread::sleep_for(1s);
    cout << "1" << endl;
    this_thread::sleep_for(1s);
    cout << "GO" << endl;

    auto start = Time::now();
    getline(cin, text);
    auto stop = Time::now();

    auto mpw = (stop - start) / 1.0min / 12;
    float wpm = 1/mpw;

    if (ctext == text)
    {
        cout << "Correct! WPM: " << wpm << '\n';
    }
    else
    {
        cout << "You had some errors. Your WPM: " << wpm << '\n';
    }
}