donkey
donkey

Reputation: 513

is there an any way to discard '\n'?

I am trying to to record response by the user(using getchar()). I am having issues with '\n' sticking in buffer. If I use fgets(char* buf, .. , ..), '\n' again goes into buf and you have to include '\n' at the end of the test string. when using string.h functions (like strcmp()). Is there any clean way of writing code for such purposes.

    #include<stdio.h>
    #include<string.h>
    int main()
    {
    char buf[100];
    fgets(buf, 3, stdin);
    puts(buf);
    int i = strcmp("p\n", buf);
    printf("%d", i);
    //if (!strcmp("CLock to random\n", buf))
    //{
    //puts("sucess");
    //}
    char c;
    c = getchar();
    putchar(c);
    return 0;
    }

Now I want to record response(single character 'p'). If I use getchar(), in place of fgets(), program skips second getchar()( c = '\n'). If I use the current code, i have to include \n in strcmp() every time.

Upvotes: 4

Views: 253

Answers (2)

BLUEPIXY
BLUEPIXY

Reputation: 40145

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

char* chomp(char* str){
    size_t len = strlen(str);
    if(len>0 && str[len-1] == '\n')
        str[len-1] = '\0';
    return str;
}

int main(void){
    char buf[128];

    fgets(buf, sizeof(buf), stdin);
    printf("<%s>\n", buf);  //include newline
    printf("<%s>\n", chomp(buf));//drop tail newline
    printf("<%s>\n", chomp(buf));//NC

   return 0;
}

Upvotes: 2

user529758
user529758

Reputation:

If you want to discard the \n:

char buf[0x1000];
fgets(buf, sizeof(buf), stdin);
char *p = strchr(buf, '\n');
if (p) *p = 0;

Upvotes: 3

Related Questions