Reputation: 33
I'm trying to get ready for an exam for my year one programming course. I need my if
statement to return a sum with the number of characters before the user enters a 'p'
or 'P'
in a 10 character string. However, I can't seem to get it to count properly.
for (int i=0;i<=strlen(toProcess);i++){
if (toProcess[i]!='p'|| toProcess[i]!='P'){
sum=sum+1;
printf("%c ", toProcess[i]);
}
}
Upvotes: 0
Views: 79
Reputation: 881383
if (toProcess[i] != 'p' || toProcess[i] != 'P') {
Short of some quantum-mechanical-weird universe where something can be p
and P
at the same time, this condition will always be true(a):
p
nor P
: true || true -> true
.p
: false || true -> true
.P
: true || false -> true
.You need to use &&
for this particular case:
p
nor P
: true && true -> true
.p
: false && true -> false
.P
: true && false -> false
.And, of course, if you want to stop after finding the first p
or P
, you need to break out of the loop as well. You could either do that as an else
block for your (corrected) condition:
int sum = 0; // probably needed.
size_t len = strlen(toProcess); // cache for efficiency.
for (int i = 0; i < len); i++) {
if (toProcess[i] != 'p' && toProcess[i] != 'P') {
sum++;
printf("%c ", toProcess[i]);
} else {
break;
}
}
Or, you could change the condition to just be an early exit:
int sum = 0; // probably needed.
size_t len = strlen(toProcess); // cache for efficiency.
for (int i = 0; i < len); i++) {
if (toProcess[i] == 'p' || toProcess[i] == 'P')
break;
sum++;
printf("%c ", toProcess[i]);
}
You'll notice in both those cases, I've also changed <=
into <
. A ten-character string has character positions 0..9
so those are generally the indexes you should use. I've also ensured that, for efficiency, we're only calling strlen()
once, on the assumption the string doesn't change while processing.
(a) Of course, my physicist buddies will tell me that the act of observing toProcess[i]
will cause it to collapse to one or the other, so this isn't technically correct. Leave it to physicists to spoil an otherwise funny physics joke :-)
Upvotes: 3