C - 按回车键退出循环

时间:2016-12-12 21:40:56

标签: c loops scanf

我试图从数组中打印一串字符,并在每次按下"输入"时结束循环。键。

int i;
char charArry[MAXARY];

printf("Input an array of chars: \n\n");

for (i = 0; i < MAXARY && charArry[i] != 13; i++)
{
    scanf(" %c", &charArry[i]);
}

for (i = 0; i < MAXARY; i++)
{
    printf(" %c", charArry[i]);
}

出于某种原因,每当我按下Enter键时,它只会转到一个新行,而不是打破循环。有什么建议吗?

P.S MAXARY是数组长度的常量,目前为20。

2 个答案:

答案 0 :(得分:2)

你接近这个工作。虽然我同意应该避免使用scanf,但请参阅:Why does everyone say not to use scanf? What should I use instead?,这是因为您的程序没有按照逻辑错误执行的操作。

你的for循环状态:

for (i = 0; i < MAXARY && charArry[i] != 13; i++)

现在重新讨论for循环的工作原理,你有:

1. initalization (i=0)
2. conditional check (i < MAXARY && charArry[i] != 13)
3.        conditional block (scanf)
4. increment (i++)
5. return to 2

您会注意到charArray[i] != 13i递增后发生\r次检查。因此,您不会检查您刚读过的字符,而是查看charArray [i]中的下一个字符。这就是为什么你永远不会打破for (i = 0; i < MAXARY; i++) { int result = scanf("%c", &charArry[i]); if( result != 1 || charArry[i] == '\n' ) break; } 字符的循环。

推荐的修复方法是:

i

\r是读取的字符时,哪些检查scanf成功并且charArry。

另请注意,chux指出\r字符是carrage返回,而不是换行符。因此,只有在Windows上工作时,此检查才有效(因为unix不使用\n)。如果您想要独立于平台,请使用import UIKit import Alamofire import SwiftyJSON var companyController: CompanyController? let stockUrl = "https://query.yahooapis.com/v1/public/yql?q=select%20symbol%2C%20Ask%2C%20YearHigh%2C%20YearLow%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22AAPL%22%2C%22GOOG%22%2C%22TWTR%22%2C%22TSLA%22%2C%20%22SSNLF%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys" let companies = companyList() class Company: NSObject { var companyName: String var companyLogo: String var stockPrice: String init(companyName:String, companyLogo:String, stockPrice:String) { self.companyName = companyName self.companyLogo = companyLogo self.stockPrice = stockPrice } } func stockFetcher(completion: @escaping (String?) -> Void) { Alamofire.request(stockUrl).responseJSON { (responseData) -> Void in if((responseData.result.value) != nil) { let json = JSON(responseData.result.value!) if let appleStockPrice = json["query"]["results"]["quote"][0]["Ask"].string { completion(appleStockPrice) } if let googleStockPrice = json["query"]["results"]["quote"][1]["Ask"].string { completion(googleStockPrice) } if let twitterStockPrice = json["query"]["results"]["quote"][2]["Ask"].string { completion(twitterStockPrice) } if let teslaStockPrice = json["query"]["results"]["quote"][3]["Ask"].string { completion(teslaStockPrice) } if let samsungStockPrice = json["query"]["results"]["quote"][4]["Ask"].string { completion(samsungStockPrice) } if let microsoftStockPrice = json["query"]["results"]["quote"][5]["Ask"].string { completion(microsoftStockPrice) } print(json) } } } func companyList() -> [Company] { let apple = Company(companyName: "Apple", companyLogo: "AppleLogo", stockPrice: appleStockPrice!) let google = Company(companyName: "Google", companyLogo: "GoogleLogo", stockPrice: googleStockPrice!) let twitter = Company(companyName: "Twitter", companyLogo: "TwitterLogo", stockPrice: twitterStockPrice!) let tesla = Company(companyName: "Tesla", companyLogo: "TeslaLogo", stockPrice: teslaStockPrice!) let samsung = Company(companyName: "Samsung", companyLogo: "SamsungLogo", stockPrice: samsungStockPrice!) let microsoft = Company(companyName: "Microsoft", companyLogo: "MicrosoftLogo", stockPrice: microsoftStockPrice!) return [apple, google, twitter, tesla, samsung, microsoft] }

答案 1 :(得分:2)

  

出于某种原因,每当我按下Enter键时,它只会转到一个新行,而不是打破循环。

scanf(" %c", &charArry[i]);格式的空格指示scanf()使用并丢弃所有可选的前导空格。永远不会为charArry[i]分配13,因为13通常是'\r',是一个空格。

回车键通常会翻译为'\n'

请勿测试尚未指定的值@Red Alert

//                        v---------v not assigned yet.       
for (i = 0; i < MAXARY && charArry[i] != 13

修复代码

int i;
char charArry[MAXARY];

printf("Input an array of chars: \n\n");

for (i = 0; i < MAXARY; i++) {
  if (scanf("%c", &charArry[i]) != 1) break;  // End of file or error occurred
  // If enter key encountered
  // Usualy the charArry[i] == '\r' is not needed.
  if (charArry[i] == '\n' ||  charArry[i] == '\r') break;
}

// Only print out characters that were read.
int j;
for (j = 0; j < i; j++) {
    printf("%c", charArry[j]);
}