char myChar;
要明确以上是我的意思是"空"值。
while(conditions)
{
userInput
if(userInput)
{do stuff}
assign userInput empty value *where I need help
}
如何将char值重置为空,以防止在使用以前的userInput循环后运行if语句?我读到你不能给char指定一个指针值(null),然后我会做什么?
答案 0 :(得分:1)
您可以将userInput
设置为例如NUL
这样的字符:
while (conditions)
{
char userInput = ...;
if ('\0' != userInput)
{
// Do stuff.
}
else
{
break;
}
userInput = '\0';
}
但是,用于读取输入的方法会影响最明智的操作。用户可以输入例如换行符表示他们不想继续。
答案 1 :(得分:0)
定义新变量时,其值不是“空”而是单位化。试图读取未初始化的变量是undefined behaviour,并且不会为您提供所需的结果。
如果你想让它处于某种状态,你需要指定一个你知道不会以任何其他方式获得的值,最好的值是NULL
,但你可以选择任何一个您知道不会分配变量的值。如果您不能保证任何此类值,则必须使用另一个变量(大多数拟合为bool
)。最好在struct
char userInput = NULL;
//...
while (condition)
{
userInput = GetInput();
if (userInput)
{
//do stuff
}
userInput = NULL;
}
使用结构和额外的状态变量:
struct UserInput { // Declare UserInput struct type
bool initiated;
char c;
} userInput; // create a variable userInput of type UserInput
userInput.initiated = false;
//...
while (condition)
{
userInput = GetUserInput(); //GetUserInput also changes the value of initiated to true
if (userInput.initiated)
{
//do stuff
}
userInput.initiated = false;
}