控制台中循环内的输入和输出 我正在编写一个C++程序来处理书籍。用户需要插入3本书的标题、价格和卷数。我没有在代码中包含书类,因为它与我的问题无关

控制台中循环内的输入和输出 我正在编写一个C++程序来处理书籍。用户需要插入3本书的标题、价格和卷数。我没有在代码中包含书类,因为它与我的问题无关,c++,cin,cout,clion,C++,Cin,Cout,Clion,我被困在用户需要在循环中输入值的地方。当我测试这个程序时,控制台总是在看似随机的时间进行窃听。(即,它显示“给书p”,而不是完整的句子,并等待输入) 我在其他答案中读到,我应该在每次调用cin>后使用cin.ignore(),以便忽略用户按enter键时放入流中的\n,但这并不能解决我的问题 你知道我做错了什么吗 #include <iostream> #include <sstream> using namespace std; int main() { s

我被困在用户需要在循环中输入值的地方。当我测试这个程序时,控制台总是在看似随机的时间进行窃听。(即,它显示
“给书p”
,而不是完整的句子,并等待输入)

我在其他答案中读到,我应该在每次调用
cin>
后使用
cin.ignore()
,以便忽略用户按enter键时放入流中的
\n
,但这并不能解决我的问题

你知道我做错了什么吗

#include <iostream>
#include <sstream>

using namespace std;

int main() {
    string title;
    double price;
    int volumes;

    for (int i=0; i<3;i++){
        cout << "Give book title : " << endl;
        getline (cin, title);
        cout << "Give book price : " << endl;
        cin >> price;
        cin.ignore();
        cout << "Give number of volumes : " << endl;
        cin >> volumes;
        cin.ignore();
    }

    return 0;
}
#包括
#包括
使用名称空间std;
int main(){
字符串标题;
双倍价格;
国际卷;

对于(int i=0;i您可以使用
std::ws
作为
getline()
方法的参数来实现您的目标

以下代码将用于您的目的:

#include <iostream>

int main() {
    std::string title;
    double price;
    int volumes;

    for (int i=0; i<3;i++){
        std::cout << "Give book title : ";
        std::getline(std::cin >> std::ws, title);
        std::cout << "Give book price : ";
        std::cin >> price;
        std::cout << "Give number of volumes : ";
        std::cin >> volumes;
        std::cout<<"Title: "<<title<<" costs "<<price<<" for "<<volumes<<" volumes.\n";
    }

     return 0;
}

我建议不要把
getline
cin
混在一起。正如你所发现的那样,这会让人头疼。@bolov我还能如何处理字符串的输入呢?@thelaw看看这一点(第2点):您的平台是什么?我无法重现该问题。您的代码也可以完美地作为Linux控制台应用程序运行。可能您应该尝试将其作为windows控制台应用程序运行(在CLion控制台之外,只需从命令提示符下运行.exe)
#include <iostream>

int main() {
    std::string title;
    double price;
    int volumes;

    for (int i=0; i<3;i++){
        std::cout << "Give book title : ";
        std::getline(std::cin >> std::ws, title);
        std::cout << "Give book price : ";
        std::cin >> price;
        std::cout << "Give number of volumes : ";
        std::cin >> volumes;
        std::cout<<"Title: "<<title<<" costs "<<price<<" for "<<volumes<<" volumes.\n";
    }

     return 0;
}
Give book title : Harry Potter
Give book price : 12.5
Give number of volumes : 5
Title: Harry Potter costs 12.5 for 5 volumes.
Give book title : James Anderson
Give book price : 45.6
Give number of volumes : 7
Title: James Anderson costs 45.6 for 7 volumes.
Give book title : Lucas Empire
Give book price : 34.5
Give number of volumes : 7
Title: Lucas Empire costs 34.5 for 7 volumes.