gpt4 book ai didi

c++ - cin >> int 给定一个字符串,将 int 赋值给 0

转载 作者:太空狗 更新时间:2023-10-29 23:11:00 27 4
gpt4 key购买 nike

我遇到的问题是,如果您输入任何字符串,cin 会将 int 赋值给 0。一个有趣的发现是,如果您稍后将 cin 赋给一个字符串,您将得到您为 int 输入的整个字符串. cin.fail() 出于某种原因总是返回 true,即使使用 cin.ignore() 等,if(cin >> startingPosition) 也总是返回 true。那么,我怎样才能让它捕捉到甚至识别出它是一个字符串而不是一个整数呢?比如,如果它是一个字符串,我如何让它再次循环?

int getUserPosition(bool volatileCall = false) {
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
int startingPosition;
cin >> startingPosition;
while (startingPosition >= WIDTH || startingPosition < 0) {
cout << "Invalid slot." << endl << endl;

if (volatileCall) {
return -1;
}
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
cin >> startingPosition;
cout << startingPosition << endl;

}
return startingPosition;
}

最佳答案

你必须保存cin的结果

isNumber = (cin >> startPosition);

整个代码看起来像

int getUserPosition(bool volatileCall = false) {
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
int startingPosition;
bool isNumber = (cin >> startingPosition);
while(isNumber && (startingPosition >= WIDTH || startingPosition < 0)) {
cout << "Invalid slot." << endl << endl;
if (volatileCall) {
return -1;
}
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
isNumber = (cin >> startingPosition);
cout << startingPosition << endl;
}
return startingPosition;
}

关于c++ - cin >> int 给定一个字符串,将 int 赋值给 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52925224/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com