【发布时间】:2012-08-15 00:09:33
【问题描述】:
我是 Objective-C 的新手,这确实是我的第一个交互式程序。我已经学习了大约 2 周了。
所以,我的问题是:通常我注意到,当您连续有多个 scanf 时,它们每个都在等待输入 - 但是在这种情况下,我要求提供帐户所有者姓名和余额 - 它触发两个 NSLog 函数,而不是等待第一个输入。
这是我的主要内容:
int main(int argc, char* argV[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
bank *columbiaBank = [[bank alloc] init];
int iteration = 0;
while (true) {
int selection = 0;
NSLog(@"\n1. Add Account \n2. Remove Account \n3. Modify Account \nWhat would you like to do?:");
scanf("%i", &selection);
if (selection == 1) {
NSLog(@"\nEnter account owner:");
char accountOwner;
scanf("%c", &accountOwner);
NSLog(@"\nEnter opening balance:");
float openingBalance;
scanf("%f", &openingBalance);
// create and add new account
bankAccount *newAccount = [[bankAccount alloc] initWithProps:[NSString stringWithFormat:@"%c", accountOwner] :[NSString stringWithFormat:@"%i", iteration] :openingBalance];
[columbiaBank addAccount:newAccount];
[newAccount release];
NSLog(@"\nAccount successfully added!");
} else if (selection == 2) {
NSLog(@"\nEnter account id:");
int accountId;
scanf("%i", &accountId);
// remove account
[columbiaBank removeAccount:[NSString stringWithFormat:@"%i", accountId]];
NSLog(@"\nAccount successfully removed!");
} else if (selection == 3) {
NSLog(@"\nThe bank currently has %i accounts.", columbiaBank.totalAccounts);
NSLog(@"\nThe bank's current balance from all accounts is $%f", columbiaBank.totalBankBalance);
NSLog(@"\n-- Output of all account info --");
[columbiaBank printAccounts];
} else {
NSLog(@"You did not enter a valid action.");
}
iteration++;
}
[columbiaBank release];
[pool drain];
return false;
}
【问题讨论】:
-
scanf使用%c格式说明符 will leave the new-line in the buffer after only consuming one character。由于缓冲区不为空,因此\n会立即被以下scanf使用%f消耗——这将分配给它0。
标签: objective-c c scanf foundation