我想通过使用获取字符串作为输入scanf,如果字符串只是空格或空白,我必须打印错误消息。
这是我尝试做的:
char string1[20]
scanf("%s",string1)
if(string1=='')
print error message
Run Code Online (Sandbox Code Playgroud)
但这没用,实际上我没想到它能用,因为它string1是一个字符数组。
有什么提示怎么做吗?
您应该注意,该scanf函数绝不会扫描仅包含空格的字符串。而是检查函数的返回值,如果它(在您的情况下)小于一个,则它无法读取字符串。
您可能想使用fgets读取一行,删除尾随的换行符,然后检查字符串中的每个字符是否为空格(使用isspace 函数)。
像这样:
char string1[20];
if (fgets(string1, sizeof(string1), stdin) != NULL)
{
/* Remove the trailing newline left by the `fgets` function */
/* This is done by changing the last character (which is the newline)
* to the string terminator character
*/
string1[strlen(string1) - 1] = '\0';
/* Now "remove" leading whitespace */
for (char *ptr = string1; *ptr != '\0' && isspace(*ptr); ++ptr)
;
/* After the above loop, `*ptr` will either be the string terminator,
* in which case the string was all blanks, or else `ptr` will be
* pointing to the actual text
*/
if (*ptr == '\0')
{
/* Error, string was empty */
}
else
{
/* Success, `ptr` points to the input */
/* Note: The string may contain trailing whitespace */
}
}
Run Code Online (Sandbox Code Playgroud)