Hi, i am reading in a date string as hh:mm:ss and trying to store the values in hh, mm, and ss. the input would read as something like 21:43:33. I have looked at some functions like strtok and strchr but not really sure which is most effective. Would appreciate it if someone has an easy answer to this Thanks
strtok is the best way for this, Code: #include <stdio.h> #include <string.h> int main () { char str[] ="15:30:12"; char *hh,*mm,*ss; hh = strtok (str,":"); mm = strtok (NULL,":"); ss = strtok (NULL,":"); printf("%s,%s,%s",hh,mm,ss); return 0; }
here is the Code for what you need ..try this Code: #include <string> #include <iostream> using namespace std; int splitString( string input,string seperatior); int main() { std::string input = "21:30:33"; splitString (input,":"); return 0; } int splitString (string input,string seperator) { size_t i = input.find(seperator); if ( i!=string::npos ) { size_t y = 0; string hour = ""; if (!input.empty()) { while ( y!=i) { hour += input[y++]; } } cout << hour << endl; } return 0; }
Rather than calling lots of functions, if the input format is guaranteed you can do something like: Code: char *tm="21:43:33"; int hh=tm[0]*10+tm[1]-'0'*11; int mm=tm[3]*10+tm[4]-'0'*11; int ss=tm[6]*10+tm[7]-'0'*11; especially if after splitting the strings into smaller strings you're then converting them to numbers.