我想通过使用scanf
获取字符串作为输入,如果字符串只是一个空格或空白我必须打印错误消息。
这就是我试图做的事情:
char string1[20]
scanf("%s",string1)
if(string1=='')
print error message
但这不起作用,实际上我没想到它会起作用,因为string1
是一系列字符。
有什么提示怎么办?
您应该注意,scanf
函数永远不会扫描只有空格的字符串。而是检查函数的返回值,如果它(在您的情况下)小于1则无法读取字符串。
您可能希望使用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 */
}
}
scanf()
并不总是跳过领先的空白。
选择格式指定像“%s
”,“%d
”,“%f
”做跳过前导空白。 (空格)。
其他格式指定像“%c
”,“%[]
”,“%n
”不要跳过跳过前导空格。
扫描并查找空格。 (string1可能包含空格)
char string1[20];
// Scan in up to 19 non-LineFeed chars, then the next char (assumed \n)
int result = scanf("%19[^\n]%*c", string1);
if (result < 0) handle_IOError_or_EOF();
else if (result == 0) handle_nothing_entered();
else {
const char *p = string1;
while (isspace(*p)) p++;
if (*p == '\0')
print error message
}
首先,如果你在格式说明符之前放置一个空格(或其他空白字符,如scanf
或'\n'
),'\t'
将跳过任何空格,如scanf(" %s", &str)
其次,if(string1=='')
会将char指针string1
与空白char ''
进行比较,因为现有变量的地址将为非NULL,所以它永远不会成立。也就是说,C中的''
没有“空白”字符。您需要获取行输入并解析它是空行还是只包含空格