我需要要求用户输入三角形的值和字符
I need to ask user to input a value for the triangle and a character for it?
我几乎完成了代码,我只需要弄清楚如何使用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());
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 指向指向字符数组的指针数组的指针
- 如何用转义符替换字符串中的所有特殊字符
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 比较字符数组
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 绘制旋转的三角形
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 我需要要求用户输入三角形的值和字符