user2139009
user2139009

Reputation: 35

How to check for new lines and carriage returns in C

So I'm trying to figure out why the following C code doesn't work:

int isBlank(char *s){
    for(;*s != '\0';s++){
        if(*s != '\n' || *s != '\r'){
            return 0;
        }
    }
    return 1;
}

The idea is that it should return 0 if it hits anything BUT a \n or \r character otherwise it will return 1. But it seems to return 0 for almost any line? I'm sure there is something really stupid I'm missing here. :(

Upvotes: 1

Views: 1559

Answers (3)

Dmytro
Dmytro

Reputation: 5213

it works if you replace || with &&

#include <stdio.h>

int isBlank(char *s)
{
    for (;*s != '\0'; s++) {
        if (*s != '\n' && *s != '\r') {
            return 0;
        }
    } 
    return 1;
}

int main()
{
    char *msg1 = "hello, world\n";
    char *msg2 = "hello, world!";
    char *msg3 = "";
    char *msg4 = "\r";
    printf("msg1 is blank: %i\n", isBlank(msg1));
    printf("msg2 is blank: %i\n", isBlank(msg2));
    printf("msg3 is blank: %i\n", isBlank(msg3));
    printf("msg4 is blank: %i\n", isBlank(msg4));


    return 0;
}

Upvotes: 0

Jay
Jay

Reputation: 24895

 But it seems to return 0 for almost any line?

Most of the lines will have \n\r only at the end of the line. In your code, you return 0 the moment you encounter any character other than \n or \r which is the reason why you always get a 0.

Upvotes: 2

Paul R
Paul R

Reputation: 212939

Your logic is slightly off - change:

    if(*s != '\n' || *s != '\r'){

to:

    if(*s != '\n' && *s != '\r'){

Upvotes: 5

Related Questions