繁体   English   中英

如何在 c++ 中进行格式化输入?

[英]how to take formatted input in c++?

好吧,我知道如何在 c 中执行此操作,例如:

#include <stdio.h>

int main()
{
    int a,b,c;
    scanf("%d:%d,%d",&a,&b,&c);
    printf("%d %d %d",a,b,c);

    return 0;
}

但是为了在 c++ 中执行此操作? cin可以像scanf一样使用吗?

由于输入格式是"%H:%M,%s"我怀疑时间是输入。
在这种情况下,有更好更简单的方法来做到这一点:

    std::tm t{};
    while(std::cin >> std::get_time(&t, "%H:%M,%S")) {
        std::cout << std::put_time(&t, "%H %M %S") << '\n';
    }

https://godbolt.org/z/Y5o9cYc4G

正则表达式示例:

#include <iostream>
#include <regex>
#include <string>

int main()
{
    bool input_ok{ false };

    std::regex rx{ "(\\d+):(\\d+).(\\d+)" }; // regex of groups
    std::smatch match;
    std::string input;

    do
    {
        std::cout << "Enter value (format d:d.d, where d can be one ore more number ) : ";
        std::cin >> input;
    }
    while (!std::regex_match(input, match, rx));

    // match[0] will contain full match
    // match[1] will contain first digits, match[2] second group of digits

    std::cout << "first group of digits  : " << std::stoi(match[1]) << "\n";
    std::cout << "second group of digits : " << std::stoi(match[2]) << "\n";
    std::cout << "third group of digits : " << std::stoi(match[3]) << "\n";
    
    return 0;
}

简单的解决方案:

您可以使用多个>>操作,并将每个分隔符存储为charstd::string

例如:

int minutes, seconds, milliseconds;
char tmp1, tmp2;
cin >> minutes >> tmp1 >> seconds >> tmp2 >> milliseconds;
if (tmp1 != ':' || tmp2 != '.')
    cout << "Error in the input!";
else
    cout << minutes << ' ' << seconds << ' ' << milliseconds;

复杂的解决方案:

使用std::regex ,这是在另一篇文章中写的。

int a,b,c;
cin>>a>>b>>c;

string resultString = "s1:s2.s3";
resultString=resultString.replace(s1,a);
resultString=resultString.replace(s2,b);
resultString=resultString.replace(s3,c);
cout<<resultString;
return 0;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM