1

I need to do something when the user presses only enter without any input but that empty. When the user's input is something, \0 is always right behind the last char. For example

input:hello world

\0 is always in prom[11] but when user press only enter \0 isn't there.

char prom[100];
scanf("%[^\n]", prom); 
if (prom[0] == '\0'){ //if user press enter 
//do something
}
4
  • 1
    This will be easier if you use fgets (or even better, getline, but not all systems provide that) instead of scanf. Commented Mar 20, 2019 at 15:34
  • if scanf has a matching failure then the contents of the array are indeterminate... Commented Mar 20, 2019 at 15:38
  • i cant use fgets beacause fgets ends with ascii char 10 and in my program i need scan all ascii from 0 to 127 Commented Mar 20, 2019 at 15:49
  • Ohh maybe i cant use it because \0 is also in ascii as 0 and with fgets its working. Thank you Commented Mar 20, 2019 at 15:54

3 Answers 3

1

NEVER EVER SCANF ARBITRARY LENGTH STRINGS. It's a source of security holes and general source of errors you will have a great trouble to find later on. You may use scanf to look for strings if you implicitly specify the maximum length of the string to read (read about the scanf format specifiers). But in your situation it is faster and safer just to use fgets. Read the string. Check if you actually have read it (by the return value of fgets) and then check if the first character (if it actually exists) is '\n'. If it is so then the user has prompted an empty string.

Besides as you have got your string you can safely parse it with sscanf for the message you need to parse.

Sign up to request clarification or add additional context in comments.

Comments

0

fgets() is solution for condition if prom[0] == '\n'

Comments

0

scanf() returns the number of converted chars. Test the returned value against 0 to see if no conversion has been done.

1 Comment

It returns the number of sucessfully matched and assigned to specifiers, not the number of characters. So testing against zero is an ok answer, but testing for returning 1 is probably better (to handle EOF more cleanly)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.