Home > OS >  How to split a string which is taken input as char pointer?
How to split a string which is taken input as char pointer?

Time:02-20

#include<stdio.h>
#include<limits.h>
#include<math.h>
#include<stdbool.h>
#include<stddef.h>
#include<stdint.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>

int splitHourMinute(char *time){
    
    token = strtok(time, ":");
   
    while( token != NULL ) {
        printf( " %s\n", token );
    
        token = strtok(NULL, ":");
    }
    
    return 0;
    
    }

int main(){
    char* time;
    scanf("%s",time);
    
    splitHourMinute(time);
    
    return 0;
}

When I take input as character pointer (my input is 12 hour format time : 10:15) :-

char* time;
scanf("%s",time);

I get segmentation fault error because we can't modify a string literal, which is what strtok does.

So my question is there any way to split the string when we take input as character pointer ?

Please kindly don't give suggestion to take input as character array because I got a coding question in a interview where input is given character pointer which I cannot modify and I failed to do that.

CodePudding user response:

Be more clear.If you always get your input in the form hh:mm, why you don't just take the substrings ?

#include <iostream>
void splitHoursMinutes (std::string & timeString) {
    std::string hours, minutes ;
    size_t colonPosition; 
    colonPosition = timeString.find (":");
    if ((colonPosition == 0) || (colonPosition == timeString.length () - 1))
        throw std::invalid_argument("Invalid input string");
    hours = timeString.substr (0, colonPosition);
    minutes = timeString.substr (colonPosition   1, timeString.length() - 1);
    std::cout << hours << std::endl ;
    std::cout << minutes << std::endl ;
}
int main () {
    std::string inputString ;
    std::cin >> inputString ;
    try {
        splitHoursMinutes (inputString);
    } catch (std::invalid_argument & err) {
    std::cerr << err.what () << std::endl ;
    return -1;
    }
    return 0;
}

CodePudding user response:

C version.

int split_hm (char * time_string) {
  char * colon;
  colon = strchr (time_string, ':');
  if ((colon = strchr (time_string, ':')) == NULL) return -1;
  * colon = '\0';
  if ((colon == time_string) || ( *(   colon) == '\0' ))                            
      return -1;                                                                    
  printf ("%s\n%s\n", time_string, colon);                                          
  return 0;                                                                         
}                                                                                   
int main () {                                                                       
  char input_string [6];                                                            
  scanf ("%s", &input_string);          
  return split_hm (input_string);                                  
}
``
  • Related