can't tokenize a string and pass it to struct in c++

Viewed 120

i have to write a program in which i have to take time(hh:mm:ss) as string input and tokenize it using : as a delimiter and pass hours, minutes and seconds to a struct time and then display the total number of seconds. I have written the code but it's giving me error that i can't understand. This is the code:

#include<iostream>
#include<string>
using namespace std;

struct time{
   int hours;
   int minutes;
   int seconds;
  
   void Print_in_Seconds(){
       cout<<"Total Second: "<<hours*3600+minutes*60+seconds;
   }
};

time Tokenized_time(string str)
{
   time time_;
   // Get hours
   int hour1 = (int)str[1] - '0';
   int hour2 = (int)str[0] - '0';
   int hour = (hour2 * 10 + hour1 % 10);
   int count=0;
   int minute=0,second=0;
   for (int i=3; i <= 7; i++){
       if(i==3 || i==4){
       minute=minute*10+((int)(str[i]-'0'));  
       }
       else if(i==6 || i==7){
       second=second*10+((int)(str[i]-'0'));  
       }
   }
   time_.hours=hour;
   time_.minutes=minute;
   time_.seconds=second;
   return time_;

}

// Driver code
int main()
{
   time time1;
   cout<<"Enter Time- 00:00:00 Formate: ";
   string str;
   cin>>str;
   time time1=Tokenized_time(str);
   time1.print();
return 0;
}

and this is the error i'm getting

enter image description here

Any help?

1 Answers

time happens to be the name of a function in the standard C library (and incorporated into the C++ library), and by naming your struct the same, you're creating ambiguity, and according to the grammar rules of C++, the compiler must consider time to the function name, here, resulting in a compilation error.

The simplest solution is to pick a different name for your struct. You could also direct your compiler to explicitly parse time as a type:

struct time Tokenized_time(string str)

And as long as you're doing it, you might as well get rid of using namespace std in order to eliminate more opportunities for a similar kind of a headache, confusion, and unwelcome surprises.

EDIT: it may very well be the case that this is a bug in libstc++, but there's nothing you can do about it except to sit and wait for gcc to fix this bug. But you'll probably be able to work around it, like this, much faster...

Related