Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Identifying carraige return and newline in code

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
I need to determine whether a character input is a carraige return or new line. I have tried comparing the input to '\r' and '\n', but that's not working. I used strcmp, strstr, and strchr, but none give me the right results. WHile typing in the input, I hit 'enter' to accomplish the return and newline. Is that wrong? Any help is greatly appreciated. Thanks!!
 
use the hex value for carriage return which is 0x0a

#include <cstdio>

int main(int argc, char* argv[])
{

char c;
printf(&quot;enter char: &quot;);
c = getchar();

if (c == 0x0a)
printf(&quot;match\n&quot;);

else
printf(&quot;no match\n&quot;);

return 0;
}
 
That's a great answer, JTM111... and just to explain a bit further, the '0x0a' is broken down as follows:

'0x' - tells the compiler that the number which immediately follows is hexadecimal

'0a' - hexadecimal value for the 'line feed' character

The complete list of hexadecimal characters can be viewed in this table:
 
good clarification - it's not exactly obvious at first glance, thanks
 
The 'c==0x0a' is typecasting the char to an integer in order to compare the input. It translates the char that's input into an integer value as that is the larger datatype. C quite easily does this but most languages would give an error as they don't like comparing different datatypes.

This can be confusing and uses up memory as an integer datatype is larger than a char datatype so what's the point?

Use the '\r' and '\n' as it makes more sense when writing the code.

Also we may as well start using assembly if you're going to start playing with hex codes!

59Hoggbottom.
 
the solution given by jtm111 is ideal no doubt about that
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top