简体   繁体   中英

Check if user's input is empty in C with scanf

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
}

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.

如果prom [0] =='\\ n',则fgets()是条件的解决方案

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM