0
#include <stdio.h>
#include <math.h>

int main(){
    int x;
    printf("Enter The Number :");
    scanf(" %d \n" , &x);
    int xS= sqrt(x);
    printf("Square Root of The Given Number : %d" , xS);
}

after entering the value 120 , nothing is happening! I am using Clion. What do I have to Do?

3 Answers3

3

You should remove whitespace and '\n' from the format string of scanf.

An '\n' or any whitespace character in the format string of scanf consumes an entire sequence of whitespace characters in the input. So the scanf only returns when it encounters the next non-whitespace character, or the end of the input stream.

3

From the standard (but with my emphasis):

A directive composed of white-space character(s) is executed by reading input up to the first nonwhite-space character (which remains unread), or until no more characters can be read.

That means your trailing white-space directive cannot be satisfied until it detects a non-space in the input stream, which it will leave there for the next input attempt. And you certainly don't need both the space and the newline, since the latter will simply look at the same character the former did and read nothing :-)

If you had entered 120, ENTER, x, ENTER, you would have seen it continue (with the x being left in the input stream).

In fact, you would be better off just using "%d" as the input specifier. This already ignores leading white-space before attempting to read the number (meaning the initail space is unnecessary), and you should not usually concern yourself with what follows the thing you're reading.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

To be honest I couldn't tell you exactly why, but removing the \n from the scanf() seems to fix it.

Joe
  • 99
  • 5
  • 2
    It would be more better if you write this as a comment instead of an Answer. – gretal Aug 09 '22 at 04:34
  • 1
    It worked friend. Thank you Very Much, Do You Have any Idea Why was that? – Sandeepa_Dilshan Aug 09 '22 at 04:34
  • @Epsilon Great! I'm not sure unfortunately, I'm not too familiar with this language but I messed about with it and got it working. – Joe Aug 09 '22 at 04:35
  • @Epsilon, If I had to guess it would be because you're trying to get input from the user and the compiler doesn't understand why you're using a newline statement since it won't print out anyway. I could be wrong though, I hope this helps! – Joe Aug 09 '22 at 04:37
  • Thnk you Very Much – Sandeepa_Dilshan Aug 09 '22 at 04:41