【问题标题】:How do i store the output from cout into a variable如何将 cout 的输出存储到变量中
【发布时间】:2020-10-18 23:35:10
【问题描述】:

我正在制作一个 C++ 程序来根据你的父母估计你的身高。我想做它,这样我就可以输出英尺和英寸的高度。我不知道如何将 cout 的输出存储在

if (boygirl == "boy") {
    cout <<"Your estimated height is " << (mom *13/12 + dad) / 2  << " inches";
} and   else if (boygirl == "girl") {
    cout <<"Your estimated height is " << (dad+12/13 + mom) / 2   <<" inches";

到一个变量中,这样我就可以从变量中获取数据并使用它,而不是在上一步中询问英寸的结果。

您可能需要运行代码才能明白我的意思。 如果您不明白我的意思,请随时发表评论。

#include <iostream>
#include <string>

using namespace std;

void Convert(int inch) {
    int feet, inches;
    inches = inch % 12;
    feet = inch / 12;
    cout << "\n\t\tThe height in feet is " << feet << "\'" << inches << "\" " << endl;
}

int main() {
    int i = 0;
    do {
        float mom;
        float dad;
        string doyouwish;
        string boygirl;

        cout << " \n\nWELCOME TO THE C++ HEIGHT PREDICTION PROGRAM";
        cout << "\n\n INPUT GENDER TO BEGIN boy/girl: ";
        cin >> boygirl;

        cout << "How tall is your mother in inches: ";
        cin >> mom;
        cout << "How tall is your father in inches: ";
        cin >> dad;

        if (boygirl == "boy") {
            cout << "Your estimated height is " << (mom * 13 / 12 + dad) / 2 << " inches";
        } else if (boygirl == "girl") {
            cout << "Your estimated height is " << (dad + 12 / 13 + mom) / 2 << " inches";
        }

        int htInches;
        // Ask height from user
        cout << "\n\ntEnter height in Inches from the previous results: ";
        cin >> htInches;

        Convert(htInches);
        cout << "\n\n\n";

        ++i;
    } while (i < 10);
}

【问题讨论】:

  • 您应该先将结果存储在变量中,然后在您的 cout 中使用它(变量)。
  • 而不是使用 int htInches; cout > htInches;我想使用变量中的数据并将其应用于 Covert(output); cout

标签: c++ output cout


【解决方案1】:

您是否正在寻找这样的东西:

int htInches = 0;
if (boygirl == "boy") {
  htInches = (mom * 13 / 12 + dad) / 2;
} else if (boygirl == "girl") {
  htInches = (dad + 12 / 13 + mom) / 2;
}
cout << "Your estimated height is " << htInches << " inches";

计算结果,将其存储在变量中,然后打印出来。

【讨论】:

  • 我想保留英寸,但是在我的代码中我做到了,所以我也可以以英尺为单位打印结果。我不知道如何摆脱要求他们从英寸获得结果的部分。我想编辑我的代码,这样我就可以自动存储以前的结果并将其插入到转换函数中,而无需用户输入。
  • 在我的示例中,您得到了以英寸为单位的结果,分配给名为 htInches 的变量。您觉得这在哪些方面无法满足您的需求?
  • 我还需要以英尺为单位的结果。不仅仅是英寸
  • 所以请致电Convert(htInches),就像您已经在做的那样。只需删除 cin &gt;&gt; htInches; 部分(和前面的提示)。我无法理解困难的本质。
  • 我正在尝试删除用户输入,以便看起来像这样
猜你喜欢
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-27
  • 2023-02-13
  • 2011-10-08
  • 2021-12-11
相关资源
最近更新 更多