Home > Back-end >  how to take formatted input in c ?
how to take formatted input in c ?

Time:10-06

Well i know how to do this in c, for example:

#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;
}

But for to do this in c ? Can cin be use like scanf?

CodePudding user response:

Since input format is "%H:%M,%s" I suspect that a time is an input.
In such case there is better simpler way to do it:

    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

CodePudding user response:

regular expression example :

#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;
}

CodePudding user response:

Simple solution:

You can use multiple >> operations, and store every separator as char or std::string.

For example:

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;

Complex solution:

Use std::regex, which is written in another post.

CodePudding user response:

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;
  • Related