/*
* @Author: DEFT:[email protected] V:NOTFOUND6O6
* @Date: 2023-02-22 19:02:35
* @LastEditors: Please set LastEditors
* @LastEditTime: 2023-02-22 20:19:47
* @FilePath: \WenkaiC\book.cpp
* @Description:
*
* Copyright (c) 2023 by 1zPeasy, All Rights Reserved.
*/
#include <iostream>
using namespace std;
struct Books{
string name;
double price;
};
int main() {
int n;cin >> n;
cout << "輸入的數量為:" << n << endl;
struct Books b[n];
for(int i=0; i < n; i++){
//char ch;scanf("%c", &ch);
cin.ignore(1024, '\n');
getline(cin,b[i].name);
cin >> b[i].price;
}
for(int j=0; j<n; j++){
cout << b[j].name << endl;
cout << b[j].price << endl;
}
return 0;
}
個人理解
回車換行符:回車鍵
當我們輸入2回車的時候,實際上是先在鍵盤的鍵盤緩沖區中緩沖了 2\r\n,然后再發送到緩沖區中,然后第一個cin讀取到2,然后再讀到一個非數字(\r)后結束,賦值給n,但是此時的回車換行符還在緩沖區中,但是此時在沒清空的情況下,又進行getline()函式等待輸入,此時我們在鍵盤中又開始輸入"math"回車,發送到緩沖區中,此時緩沖區中有用 \r\nmath,getline()函式讀取到\r\n結束,把前面的內容存放到b[0].name,回車符也被讀出扔掉;然后繼續下一個cin,這個時候cin讀取到緩沖區中math,m放double型別的price時,型別不匹配,復制失敗,所有b[0].price就是默認值0,然后進行第二次回圈__?____,
解決方法
原理:為什么能達到和cin.ignore型別的作用呢?
char ch;scanf("%c", &ch);
或者
原理:cin.ignore(a,ch)方法是從輸入流(cin)中提取字符,提取的字符被忽略(ignore),不被使用,它的一個常用功能就是用來清除以回車結束的輸入緩沖區的內容,消除上一次輸入對下一次輸入的影響,
cin.ignore(1024, '\n');
參考文章
【C/C++】scanf()函式用法詳解(緩沖區、格式控制、fflush)
cin.ignore()函式的用法
C++中關于 getline() 讀取緩沖區中回車,以及cin 結束符的問題
【令人煩惱困惑的scanf (共5集)】 【精準空降到 15:09】
\r \n 回車換行符詳解
getchar scanf 緩沖區 清除回車符
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/544709.html
標籤:其他
上一篇:學習筆記——Git命令
下一篇:springboot01
