C ++ - 带有指针结构的字符串输入?

时间:2010-02-08 13:28:24

标签: c++ pointers struct

如何使用指向结构的指针来获取将存储在字符串变量中的输入?我认为简单地将pz-> szCompany传递给getline()的行为与我使用过的相同。在普通的Pizza实例上运算符(而不是指针),但是当我运行这个程序时,它会完全跳过公司名称提示。

// Parts of the program omitted.
struct Pizza {
    string szCompany;
    float diameter;
    float weight;
};
Pizza* pz = new Pizza;

cout << "Enter the weight: ";
cin >> pz->weight;

cout << "Enter the company name: ";
// use getline because the company name can have spaces in it.
getline(cin, pz->szCompany);

cout << "Enter the diameter: ";
cin >> pz->diameter;

cout << "\nCompany name: " << pz->szCompany;
cout << "\nWeight: " << pz->weight;
cout << "\nDiameter: " << pz->diameter;

// cannot forget this step.
delete pz;
return 0;

3 个答案:

答案 0 :(得分:7)

当您使用>>读取输入时,它会在流中留下未读的字符(那些,无法转换为整数,至少是您键入的返回字符以输入输入),以下是getline会认为它已经读过(空)行。

#include <limits>

//...
cin >> pz->diameter;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

cout << "Enter the company name: ";
// use getline because the company name can have spaces in it.
getline(cin, pz->szCompany);

您的问题与结构或指针无关,只与输入流的正常行为有关。

您可能还需要处理错误的输入。例如,输入一个预期数字的非数字会使流处于错误状态,因此除非您处理它,否则所有后续读取尝试都将失败。更好地接受Neil的建议,但是为了从用户那里获得输入,使用格式化输入的函数也可能会有意义,它会提示您直到获得有效输入:

template <class T>
T input(const std::string& prompt, const std::string& error_prompt)
{
    std::cout << prompt;
    T result;
    while (!(std::cin >> result)) {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << error_prompt;
    }
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    return result;
}

//...
pz->weight = input<float>("Enter the weight: ", "Please enter a numeric value: ");

答案 1 :(得分:2)

这与指向结构实例的指针无关。将行输入与格式化输入混合在一起并不是一个好主意。实际上,根本不使用交互式输入流中的格式化输入。您应该使用getline()读取每个输入,然后转换为所需的类型。

答案 2 :(得分:2)

添加:

cout << "Enter the company name: " << std::endl;

cout << "Enter the company name: ";
cout.flush();

您关注流缓冲化的问题