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

时间:2021-03-04 08:42:28

Case 3 is an option to add a book to the structure. 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?

案例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;

        }

1 个解决方案

#1


4  

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. So for numbers you also need to use std::getline(). But in this case you need to convert the value to an integer.

读取数字时的输入操作符>>也将停留在空格或换行符处(将它们留在输入流上)。因此,当你回到下一本书时,输入流上仍然有一个'\ 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 ;

#1


4  

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. So for numbers you also need to use std::getline(). But in this case you need to convert the value to an integer.

读取数字时的输入操作符>>也将停留在空格或换行符处(将它们留在输入流上)。因此,当你回到下一本书时,输入流上仍然有一个'\ 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 ;