Hi! I need to create a really simple program where the input is any ol' positive integer and the program outputs something like this:
Input: 5
Output:
_____5
____4
___3
__2
_1
With the underscores being spaces instead and the amount of spaces corresponding to the particular number.
When I run the code I posted below, it has the sequence start at one less than the input (so, 4 in the example) and only displayed a few of the descending numbers but not all (so, they didn't go all the way down to 1). I was wondering how I could fix this. If anyone is willing to help, it is greatly appreciated! Thank you!
//Declare Variables
int number; //user inputs a number
//Prompt User
cout<<"Enter a Positive Integer and The Program Will ""Output a Particular Pattern Accordingly."<<endl;
cin>>number;
//Produce Pattern that Depends on Input Integer
int temp = number;
for(int i = 0 ; i <= number ; i++)
{
for(int j = 0 ; j <= temp ; j++)
{
cout<<" ";
}
number--;
temp--;
cout<<number;
cout<<endl;
}
#include <iostream>
#include <string>
#include <sstream>
usingnamespace std;
int main()
{
int number;
cout << "Enter a positive integer and the program will output a particular pattern accordingly.\n";
cin >> number;
int temp = number;
for (int i = number; i >= 0; i--)
{
string s = "";
for (int j = 0; j < i; j++)
s.append("_");
std::ostringstream convert;
convert << i;
string result = convert.str();
s.append(result);
cout << s << endl;
}
}
However, I haven't learned about ostringstream and converting to a string so do you mind explaining it to me or maybe showing another way to make this program without it? Sorry >__<"
Sure thing ceci! I have some examples that I hope will help you understand a little ostringstream better. You should really look more into ostringstream and istringstream, it will help you in the long run!
ostringstream is part of the c++ stream library(sstream to be exact). It allows you to convert a number to a string in two steps(see main()).
1. Outputting the value of the number to the stream( << operator)
2. Getting the string with the contents of the stream(str())
main_error() is a representation of something I did before while working on this initially. I included this function to show what you shouldn't do in this situation.
#include <iostream>
#include <string>
#include <sstream>
usingnamespace std;
int main_error()
{
int Num = 123; //Define variable
string sNum = (constchar*) Num; //Add a cast to Num.
std::cout << sNum << endl; //The program will crash because it is a int is incompatible to a char*.
}
int main()
{
int Num = 123;
std::ostringstream convert; //ostringstream allows to convert int to strings.
convert << Num; //Insert Num to be converted into a string. Like cout, we use the << stream operator.
string Result = convert.str(); //str() returns the string.
std::cout << Result;
}