[英]Why doesn't scanf with character set format read input in a for loop?
[英]Why doesn't my final scanf stop and read user input?
谁能告诉我为什么我的代码在我进入最后决赛之前会正常工作,我问用户是否愿意再次玩吗? 由于某种原因,该程序似乎忽略了这一行代码。 请保持谦虚,因为我是编程和尝试自学Objective-C的新手。 这个程序是典型的菜鸟,我会生成一个随机数,让用户猜测,然后问他们是否想再次玩。 谢谢。
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
int randomNumber = arc4random_uniform(100); // This is a random number generator that gens a num betw 0 and 100
int userNumber; // This is the number that the user picks intially
int attempts = 0; // This is the number of attempts the user makes during each game
int games = 0; // This is the number of games the user has played
char play = 'n'; // This is whether the user wants to play again, intially set to 'y'
scanf("%c", &play);
while (play == 'y') {
NSLog(@"Random number is: %d", randomNumber);
NSLog(@"Enter a number between 0 and 100");
scanf("%d", &userNumber);
games++; // Increment the number of games the user has played to 1
if (userNumber == randomNumber) {
attempts++;
NSLog(@"Congratulations. You guessed correctly!");
}
attempts++;
while (userNumber != randomNumber) {
if (userNumber < randomNumber) { // Guess is too low
attempts++; // attempt is incremented
NSLog(@"Too low. Try again!"); // User tries again
scanf("%d", &userNumber);
}
if (userNumber > randomNumber) { // Guess is too high
attempts++; // attempt is incremented
NSLog(@"Too high. Try again!"); // User tries again
scanf("%d", &userNumber);
}
}
NSLog(@"Congratulations. You guessed correctly!");
NSLog(@"It took you %d attempts to guess correctly", attempts);
NSLog(@"Do you want to play again?");
scanf("%c", &play); // --------- Here is where things to wrong ---------
} // while play is yes
} // autoreleasepool
return 0;
} // main
将评论转换为答案:
最终的
scanf()
会读取换行符并继续(数字不会读取换行符)。 也许在%c
之前加一个空格:scanf(" %c", &play);
检查
scanf()
的返回值,甚至可以检查读取了哪个字符。
Riposte:
%c
之前的空格可以解决问题。 有人怎么会学习这样的东西? 我认为它正在读取\\n
字符,而不是我想要读取的字符,即“ y”或“ n”。 据我了解,%d
整数不会在换行符中读取,但%c
会读吗? 那是对的吗? 防止这种情况的方法是使用空格? 我只是不知道该怎么做。
以及响应:
通过非常仔细地阅读
scanf()
的手册页,多次或经历过痛苦的经历(或通过回答有关SO的许多问题)。scanf()
系列函数非常强大,并且很难精确使用。 我通常建议使用fgets()
读取输入行:char line[4096]; if (fgets(line, sizeof(line), stdin) != 0) { ...use line... }
结合
sscanf()
来解析行中的数据。 通常,它会减少您遇到的那种意外情况。 您应该始终检查scanf()
进行的转换是否符合您的预期。
空白在scanf()
系列格式字符串中的作用非常复杂。 大多数转换说明符会自动跳过前导空格(包括换行符),因此格式字符串"%d%d"
将读取为整数值,其中第一个可以带有任意数量的空格,第二个也可以是前面带有任意数量的空格。 转换将在不能为第二个整数组成部分的第一个字符处停止(除非之前有错误)。 如果键入8
并用换行符作为输入,则转换将在换行符( \\n
)上停止,如果要读取下一个输入,则保留转换。
数字转换和字符串转换%s
都跳过前导空格。 单字符格式( %c
)和扫描集%[az]
不会跳过前导空白。
当空格字符以"%d %c"
的格式出现时,则表示数据中任意数量的空格,包括零。 因此,在以下每一行中,接收%c
格式的变量每次都会获得Z
:
123Z
123 Z
123 Z
123
Z
(对于最后的输入,最后两行被一起读取。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.