0
#include<bits/stdc++.h>
using namespace std;

int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        int h;
        string s1;
        getline(cin,s1);
        cout<<s1;
        h=10*(s1[0]-'0')+1*(s1[1]-'0');
        cout<<h;
    }
}

I gave below as input

1
11:01 PM

got this as output

-560

I want to convert the hour part of the time from string to int.

James Z
  • 11,838
  • 10
  • 25
  • 41
  • 1
    Relevant (possibly a duplicate): [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/q/21567291/580083) – Daniel Langr Feb 07 '21 at 06:21
  • This is a great chance to use a debugger to step through line by line and examine your variables in order to narrow down exactly which part does something you don't expect and what exactly it does. – chris Feb 07 '21 at 06:23
  • This resolved my problem thanks. – Adityendra Feb 07 '21 at 06:35

1 Answers1

0

Check this:

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        int h;
        string s1;
        getline(std::cin.ignore(), s1);
        //getline(cin,s1);
        cout<<s1 << endl;
        h=10*(s1[0]-'0')+1*(s1[1]-'0');
        cout<<h << endl;
    }
}

I highly encourage you to read this post to understand what makes the difference.

biqarboy
  • 815
  • 6
  • 13