我需要要求用户输入三角形的值和字符

I need to ask user to input a value for the triangle and a character for it?

本文关键字:三角形 字符 输入 用户      更新时间:2023-10-16

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

我觉得我措辞错误,基本上程序应该使用我在下面创建的函数绘制线绘制一个三角形,当我编译和运行时,如果我输入 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

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

string response;
cin >> response;

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

关于读取整数的类似问题:如何正确读取和解析来自 stdin C++的整数字符串

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

if(response == '1') {
    //...
}
for (int y=y-1; y >= 1; y=y-1)

将 y 初始化为不确定值。这意味着循环将具有随机的(可能很长)持续时间。

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

您的实现应该是这样的:

string userChoiceString;
cin >> userChoiceString;
userChoice = atoi(userChoiceString.c_str());