0

im having trouble to input data which includes space bar Using C

Clion (C99)

Inputing name of recipient ,final destination and the status of the package

char name_location_status[90];
char recipient[30];
char final_destination[50];
char status[10];


printf("Please enter , 1> Recipient-, 2> Final Destination- and 3>Delivery status :\n");

scanf("%s", name_location_status);


const char upper[2] = "-";
char *token;
token = strtok(name_location_status, upper);
int i=0;
while( i!=3,token != NULL  )
{

    (i==0) ? strcpy(recipient, token) :
    (i==1) ? strcpy(final_destination, token) :
    strcpy(status, token) ;
    i++;
    token = strtok(NULL, upper);
}

The program works fine if inputing (Rat-House-Arrived) which output (Rat House Arrived) But it wont work if the inputs contain spacebar (L Rat-Kitchen House-Not arrived) which output (L ��)

So is there a way that using scanf To input data like this ?

Blockquote(L Rat-Kitchen House-Not arrived),which is in a line

If no , can u show me da way ?To input that kind of data In a line

L.Rat
  • 39
  • 6
  • 1
    1. `scanf("%s", name_location_status);` -> `scanf("%89s", name_location_status);` Prevent buffer overruns. 2. `const char upper[2] = "-";` -> `const char upper[] = "-";` - Get the compiler to do the work. 3. Use if statements and not ternary operator `?` to make the code readable. This operator has its place but not in this code. – Ed Heal Oct 05 '18 at 01:55
  • 1
    Also `while( i!=3,token != NULL )` - Perhaps the `&&` operator and not , – Ed Heal Oct 05 '18 at 01:56
  • @Ed Heal thx for replying!! I waited a while and no one respond :v anyway , i kind of get what u mean in point 1&2 , but what the third one ? i thought show this (��) is because of spacebar which lead to wrong data error – L.Rat Oct 05 '18 at 02:05
  • @Ed Heal do u also mind to explain "Also while( i!=3,token != NULL ) - Perhaps the && operator and not " this ? im new to programming , it will help alot if u can answer it – L.Rat Oct 05 '18 at 02:06
  • Point 4 -> Use if i.e. `if (i==0) { strcpy(recipient....} else if (i==1) { strcpy(...) } else{ .....}` – Ed Heal Oct 05 '18 at 02:08
  • Please google the comma operator and compare and contrast it with the `&&` operator – Ed Heal Oct 05 '18 at 02:09
  • Yes - More readable – Ed Heal Oct 05 '18 at 02:12
  • @Ed Heal Will do sir – L.Rat Oct 05 '18 at 02:12
  • If you want to read till the end of line, you can refer to the following post https://stackoverflow.com/questions/8097620/how-to-read-from-input-until-newline-is-found-using-scanf – Anirudh Oct 05 '18 at 06:27

1 Answers1

0

instead of scanf use getline() function that seems more appropirate here

char *line = NULL;
getline(&line);
akshay kishore
  • 1,017
  • 8
  • 16