简体   繁体   English

为什么添加空格会使编译器进入无限循环?

[英]why does adding a space makes the compiler go into an infinite loop?

Case 3 is an option to add a book to the structure. 案例3是向结构添加书籍的选项。 As long as books with titles without spaces are added, they are ok, whenever I try to put a name that has a space in it, the compiler goes crazy, sorta like what it would do if you execute an infinite loop. 只要添加没有空格的书籍,它们就可以了,每当我尝试放置一个有空格的名称时,编译器就会变得疯狂,就像执行无限循环一样。 Why and what is the solution? 为什么以及解决方案是什么?

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;

        }

The input operator >> stops at space when reading strings. 输入操作符>>在读取字符串时停止在空格处。
What you want to use is std::getline . 你想要使用的是std::getline

cout << "\nPlease Enter the Title: ";
std::getline(std::cin, books[i].bookTitle);

The input operator >> when reading a number will also stop at a space or newline (leaving them on the input stream). 读取数字时的输入运算符>>也将停留在空格或换行符处(将它们留在输入流中)。 Thus when you wrap around to the next book there is still a '\\n' character on the input stream. 因此,当您回到下一本书时,输入流上仍然有一个'\\ n'字符。 So for numbers you also need to use std::getline(). 因此对于数字,您还需要使用std :: getline()。 But in this case you need to convert the value to an integer. 但在这种情况下,您需要将值转换为整数。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM