Thread: Easy code question

  1. #1
    Registered User
    Join Date
    Aug 2015
    Posts
    2

    Easy code question

    So, I wrote this:
    Code:
     
    #include <stdio.h>
    #include <ctype.h>
    
    int main() {
        char m;
        while(m=getchar() !='\n') {
                  if(isdigit(m))  printf("There is a number in line");
        }
    
    }
    I thought this will go char by char and check if any char is a digit in line. So Im wondering why it doesnt work?

  2. #2
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    That is because getchar() function requires a return key to be hit after every char you enter. As an effect you never enter the loop at all. You can read through this FAQ to find out how to read from stdin without entering 'enter'.

    FAQ > How can I get input without having the user hit [Enter]? - Cprogramming.com

    As a matter of getchar() is the function you want.

    ~H
    Life is like riding a bicycle. To keep your balance you must keep moving - Einstein

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Your problem is due to operator precedence. "!=" has higher precedence than "=". Look at this bit:

    Code:
    m=getchar() !='\n'
    This is essentially equivalent to this:

    Code:
    m= (getchar() !='\n')
    "getchar()" reads a character and checks if it is not equal to a newline. The result of this comparison (true or false) is then stored in the variable "m". This is clearly not the behavior you are expecting.

    To store the result of "getchar()" in "m" and then compare that value against the newline, you need to explicitly group the "m = getchar()" part:

    Code:
    (m=getchar()) !='\n'

  4. #4
    Registered User
    Join Date
    Aug 2015
    Posts
    2
    Thank you both for help,i understand now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 23
    Last Post: 04-20-2009, 07:35 AM
  2. Seg fault in easy, easy code
    By lisa1901 in forum C++ Programming
    Replies: 11
    Last Post: 12-10-2007, 05:28 AM
  3. show a form using code, easy question
    By Rune Hunter in forum C# Programming
    Replies: 1
    Last Post: 04-04-2005, 09:03 AM
  4. easy question about machine code
    By Jaguar in forum Tech Board
    Replies: 3
    Last Post: 10-07-2003, 09:11 AM
  5. Easy question, (should be) easy answer... ;-)
    By Unregistered in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 06-12-2002, 09:36 PM