[英]Why does the compiler executes an infinite loop upon having space as a Character?
[英]why does adding a space makes the compiler go into an infinite loop?
案例3是向結構添加書籍的選項。 只要添加沒有空格的書籍,它們就可以了,每當我嘗試放置一個有空格的名稱時,編譯器就會變得瘋狂,就像執行無限循環一樣。 為什么以及解決方案是什么?
struct bookStruct
{
string bookTitle;
int bookPageN;
int bookReview;
float bookPrice;
};
const int MAX_BOOKS=10;
case 3:
{
for(int i=0;i<MAX_BOOKS;i++)
{
if(books[i].bookTitle=="\0")
{
cout << "\nPlease Enter the Title: ";
cin >> books[i].bookTitle ;
cout << "\nPlease Enter Total Number of Pages: ";
cin >> books[i].bookPageN ;
cout << "\nPlease Enter Rating (stars): ";
cin >> books[i].bookReview ;
cout << "\nPlease Enter Price: ";
cin >> books[i].bookPrice;
cout << "\n\nBook Added.\n\n";
break;
}
}break;
}
輸入操作符>>
在讀取字符串時停止在空格處。
你想要使用的是std::getline
。
cout << "\nPlease Enter the Title: ";
std::getline(std::cin, books[i].bookTitle);
讀取數字時的輸入運算符>>
也將停留在空格或換行符處(將它們留在輸入流中)。 因此,當您回到下一本書時,輸入流上仍然有一個'\\ n'字符。 因此對於數字,您還需要使用std :: getline()。 但在這種情況下,您需要將值轉換為整數。
cout << "\nPlease Enter Total Number of Pages: ";
std::string line;
std::getline(std::cin, line);
std::stringstream linestream(line);
linestream >> books[i].bookPageN ;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.