[英]How can I make sure that my char is not a negative number
I want my for loop to break if -1 is entered but that doesn't seem to work in this case.如果输入 -1,我希望我的 for 循环中断,但在这种情况下似乎不起作用。 I've tried it a few different ways but nothing seems to make it actually break.
我已经尝试了几种不同的方法,但似乎没有什么能让它真正崩溃。
struct employee{
char name[30];
float rate;
float hrsWorked;
};
int main()
{
struct employee staff[5];
int placeholder;
for(int i = 0; i < 5; i++){
printf("Enter name: ");
scanf("%d", &placeholder);
fgets(staff[i].name, sizeof(staff[i].name), stdin);
if (staff[i].name[0] == -1){
break;
}
}
}
You are storing a string of characters in name
, so -
and 1
are two different characters.您在
name
中存储一串字符,所以-
和1
是两个不同的字符。
This should work:这应该有效:
if (staff[i].name[0] == '-' && staff[i].name[1] == '1') break;
First, name
is a char
array.首先,
name
是一个char
数组。 So, if name[0] == -1
goes straight to the ASCII representation of a char
.因此,
if name[0] == -1
直接使用char
的 ASCII 表示。 Since '-1'
is technically 2 characters, they will be separated as such: name[0] : -
, where 45 is the ASCII value, and name[1] : 1
.由于
'-1'
在技术上是 2 个字符,因此它们将按如下方式分隔: name[0] : -
,其中 45 是 ASCII 值,而name[1] : 1
。
To solve this issue, you could do this:要解决此问题,您可以这样做:
if (staff[i].name[0] == '-' && staff[i].name[1] == '1')
For more info on ASCII, https://www.ascii-code.com/有关 ASCII 的更多信息, https://www.ascii-code.com/
You can use placeholder
to break through the loop您可以使用
placeholder
来打破循环
if (placeholder == -1){
break;
}
You can also use strcmp
您也可以使用
strcmp
NOTE: must include <string.h> header file
注意:必须包含 <string.h> 头文件
if (strcmp(staff[i].name, "-1\n") == 0){
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.