0

我几乎完成了代码,我只需要弄清楚如何使用 cout 和 cin 使用户输入字符的值和三角形的高度,谢谢这是我所有的代码硬编码。

我觉得我的措辞是错误的,基本上程序应该使用我在下面创建的函数 drawline 绘制一个三角形,当我编译并运行它时,如果我输入 1,它会要求我输入用户选择它运行 if (userChoice == 1){} 基本上我想要一个 cin 和 cout 代码结构,允许他们输入 lineLength 和 displayChar 的值。

#include <iostream>
#include <string>
#include <math.h>

using namespace std;

void drawLine (int lineLength, char displayChar);
void placePoint (int lineLength) ;

int main()
{
    int userChoice = 0;
    cout << "**********************************" << endl;
    cout << "* 1 - DrawTriangle *" << endl;
    cout << "* 2 - Plot Sine graph *" << endl;
    cout << "* 3 - Exit *" << endl;
    cout << "Enter a selection, please: " << endl;
    cin >> userChoice;

    int x,y,t =0;
    char displayChar = ' ';
    int lineLength = 0;
    double sinVal= 0.00;
    double rad = 0.00;
    int plotPoint = 0;

    if (userChoice == 1)
        for (int x=1; x <= lineLength; x=x+1) {
            drawLine ( x, displayChar);
        }//end for

    for (int y=lineLength-1; y >= 1; y=y-1) {
        drawLine ( y, displayChar );
    }//end for
}//end main at this point.

void drawLine (int lineLength, char displayChar) 
{
    for (int x=1; x <= lineLength; x=x+1) {
        cout << displayChar;
    }
    cout << endl;

    for (int y=y-1; y >= 1; y=y-1) {
        cout << displayChar;
    }
    cout << endl;
} //end drawline
4

3 回答 3

0
for (int y=y-1; y >= 1; y=y-1)

将 y 初始化为一个不确定的值。这意味着循环将具有随机的、可能非常长的持续时间。

于 2012-10-12T10:04:08.333 回答
0

问题在于它cin是一个流(请参阅参考文档),因此您不能只将值流式传输到userChoice它是一个 int 中。相反,您需要使用字符串:

string response;
cin >> response;

然后,您需要使用此 SO question中的一种方法解析字符串以获取 int ,例如strtol.

在这里阅读整数的类似问题:How to proper read and parse a string of integers from stdin C++

或者,只需使用字符串response进行比较:

if(response == '1') {
    //...
}
于 2012-10-12T08:14:23.297 回答
-1

你不能cin用来设置一个整数。因为cin是流,所以可以用它来设置字符串。从那里您可以使用将字符串转换为整数atoi。您可以在cplusplus.com上查看更多详细信息。

你的实现应该是这样的:

string userChoiceString;
cin >> userChoiceString;
userChoice = atoi(userChoiceString.c_str());
于 2012-10-12T08:26:32.983 回答