-3

I would be glad if I get help with this. I am not able to accept white space in a string. I am working on socket programming using C. I tried following things. Please help me.

  1. char name[100]; fgets (name, 100, stdin);

I tried using fflush(stdin); before fgets.

  1. fgets (name, 100, stdin);

  2. scanf("%[^\n]s",name); (Ref for 1,2&3: Reading string from input with space character?)

  3. scanf("%[^\t]s",name); worked for me but I have to press tab+enter after giving input. Because of which everything I input after the name is printing on next line at the server. I want to create table-like structure. How can I accept string input with white spaces? Thank you in advance

client.c

#include <stdio.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#define SERVER_PORT 5432
#define MAX_LINE 256

struct course{
  char name[100];
  char id[20];
  int registered;
  int empty;
  char time[20];
};

int main(int argc, char * argv[])
{
    struct course c;
    FILE *fp;
    struct hostent *hp;
    struct sockaddr_in sin;
    char *host;
    char buf[MAX_LINE];
    int s, new_s,n;
    int len;
    int rec=1;
    char data[1000];
    int choice;
    char search[20], del[50];
    char add[1000]="\n";
    char avail[10],ocu[10],sem[10],id[10];


    if (argc==2) {
        host = argv[1];
    }
    else {
        fprintf(stderr, "usage: simplex-talk host\n");
    exit(1);
    }

    hp = gethostbyname(host);
    if (!hp) {
        fprintf(stderr, "simplex-talk: unknown host: %s\n", host);
        exit(1);
    }

    bzero((char *)&sin, sizeof(sin));
    sin.sin_family = AF_INET;
    bcopy(hp->h_addr, (char *)&sin.sin_addr, hp->h_length);
    sin.sin_port = htons(SERVER_PORT);

    if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
        perror("simplex-talk: socket");
        exit(1);
    }
    if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
        perror("simplex-talk: connect");
        close(s);
        exit(1);
    }


    do{
        printf("\n\n*************************************************\n");
        printf(" 1.List All \n 2.Search \n 3.Add \n 4.Delete \n 9.Quit \n");
        printf("\nPlease enter your choice: \n");
        scanf("%d",&choice);


        switch(choice)
        {
        case 1: send(s, &choice,sizeof(int), 0);
            printf("\n==============Requesting All Records..=======================\n");
            len = recv(s, &data,sizeof(data), 0);
            fputs(data,stdout);
            break;

        case 2: send(s, &choice,sizeof(int), 0);
            printf("\nPlease Enter Course Name/ID: ");
            scanf("%s",&search);
            send(s, &search,sizeof(search), 0);
            printf("\n======================Searching for The Record..================\n");
            len = recv(s, &data,sizeof(data), 0);
            fputs(data,stdout);
            break;

        case 3: send(s, &choice,sizeof(int), 0);
            printf("Press Tab And Enter After Entering Course Name...\n");
            printf("Please Enter Course ID: ");
            scanf("%s",&c.id);
            printf("Please Enter Course Name: ");
            scanf("%[^\t]s",&c.name);
            printf("No of Students Registered: ");
            scanf("%d",&c.registered);
            printf("No of Vacancies: ");
            scanf("%d",&c.empty);
            printf("Course Time: ");
            scanf("%s",&c.time);
            send(s, &c,sizeof(struct course), 0);
            printf("\nInserting New Record..\n");
            break;

        case 4: send(s, &choice,sizeof(int), 0);
            printf("Press Tab And Enter After Entering Course Name...\n");
            printf("Please Enter Course Name/ID To Drop: ");
            //scanf("%[^\t]s",&data);
            scanf("%100[^\n]", del);
            //fgets(del,sizeof(del),stdin);
            send(s, del,sizeof(del), 0);
            break;

         default: printf("Please enter valid choice...\n");
        }

    }while(choice!=0);
}
David C. Rankin
  • 69,681
  • 6
  • 44
  • 72

1 Answers1

0

To trim whitespace from a string, loop through the string until isspace returns false. You can also trim the trailing whitespace by jumping to the end of the string with strlen and working backwards with isspace. In the example shown here, we trim any leading or trailing whitespace, and print the result.

#include <ctype.h>
#include <string.h>
#include <stdio.h>

int main(){
    printf("Please enter your name: ");
    fflush(stdout);

    char buf[128];
    fgets(buf, 128, stdin);


    int start = 0;
    // remove any leading whitespace.
    while(isspace(buf[start])) start++;

    int end = strlen(buf);
    // find the first character from the end that is not whitespace
    while(end > start && isspace(buf[end - 1])) end--;

    buf[end] = '\0'; // terminate the string to trim the whitespace at the end.

    char * name = &buf[start];
    printf("Name = '%s'\n", name);
}
Mobius
  • 2,751
  • 1
  • 17
  • 27
  • Thank you so much for this code snippet. It works fine to remove whitespaces in a string. But, I want to remove whitespaces between the strings. As I am passing the structure, after giving ID, Name is appearing on the new line. Is there any way to remove such white space? – Akshay Chandrachood Oct 02 '17 at 03:56
  • in the question you want to read a string with spaces. No where else you said that you want to remove whitespaces in that string – phuclv Oct 02 '17 at 12:30
  • @Akshay C `\n` counts as whitespace, so the above function will also trim the trailing newline from your input, which you said was a problem at the server. – Mobius Oct 02 '17 at 12:49
  • so if you input "My Name\n" (since `fgets` includes the enter), it will give back "My Name" – Mobius Oct 02 '17 at 13:11
  • @LưuVĩnhPhúc Sorry for the confusion. I thought I can take care of this issue at the server side by removing the additional '\n' – Akshay Chandrachood Oct 02 '17 at 14:58
  • @AkshayC That would work too, but what is your question then? – Mobius Oct 02 '17 at 16:31
  • I was not able to do either of them. I was not able to accept the input using fgets. But my problem got solved. I could able to accept the input with whitespaces using fgets after doing following thing: //fgets will not work after using scanf //to get it work again, read the extra characters and discard char ch; while((ch= getchar()) != '\n' && ch != EOF); fgets(c.name, 100, stdin); – Akshay Chandrachood Oct 05 '17 at 03:28