ios::right only works once C++ - c++

I have no idea why ios::right works once. totally nothing
Same problem with ios::hex, ios::decimal and a few others unless I do some insane codes and get them magically work again
#include <iostream>
#include <iomanip>
using std::cout;
using std::ios;
int main() {
int len;
std::cin >> len;
// w = len + 1;
cout.width(len);
cout.setf(ios::right);
for (int s = 0; s < len; s++) {
for (int c = 0; c <= s; c++) {
cout << '#';
}
cout << '\n';
}
std::cin.get();
std::cin.get();
}
Expected Output:
#
##
###
####
#####
######
What i get:
#
##
###
####
#####
######
Tried This:
cout << ios::right << '#';
Didn't work.

You need to write cout.width(len-s);cout.setf(ios::right); inside the first loop because ios::right works only for one time. So it should be
#include <iostream>
#include <iomanip>
using std::cout;
using std::ios;
int main()
{
int len;
cin >> len;
for (int s = 0; s < len; s++)
{
cout.width(len);
cout.setf(ios::right);
for (int c = 0; c <= s; c++)
{
cout<<"#";
}
cout<<"\n";
}
std::cin.get();
std::cin.get();
}
But your code is not correct as per you required output , correct code is :
#include <iostream>
#include <iomanip>
using std::cout;
using std::ios;
int main()
{
int len;
cin >> len;
for (int s = 0; s < len; s++)
{
cout.width(len-s); // to align properly
cout.setf(ios::right);
for (int c = 0; c <= s; c++)
{
cout<<"#";
}
cout<<"\n";
}
std::cin.get();
std::cin.get();
}

The problem here is not that right is temporary, but that the width is temporary, so the next character being output does not use the width given - in fact that's a good thing, or your second line would be # #, so you probably don't want that!
The solution is to move the width call into the outer of your two loops (and recalculated the width accordingly as you get wider and wider output).
I'm intentionally not writing how you should do this, as you need to practice thinking about how thing work, not practicing CTRL-C/CTRL-V.

A shorter and simpler way of doing what you want
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; ++i) {
for (int j = n; j > 0; --j)
cout << (i >= j ? "#" : " ");
cout << endl;
}
return 0;
}
Input
6
Output
#
##
###
####
#####
######
See http://ideone.com/fbrfpe demo.

Related

C++ Hiding an Input Whilst its Being Typed in Windows Console

I'm pretty new to C++, and I'm trying to code a Wordle-like game, for 2 players using Visual Studio, to run in the windows cmd.
I want the user string input to be replaced with a '' or '*' character/symbol whilst it's being typed. I want to do this only using iostream, I have come across various solutions online, but none without importing any additional libraries (the solutions online usually use getch(), which needs an additional library)
My relevant (pretty bare) code is as follows:
#include <iostream>
using namespace std;
char a[5];
string str;
int main()
{
cout << "\nSet your Wordle first: ";
cin >> str;
for (int x = 0; x < 5; x++) {
a[x] = str[x];
}
return 0;
}
So I guess, as characters for 'str' are being typed, a '*' would be outputted on the windows console instead.
Any help or hints would be greatly appreciated, Thanks!
Note: Scroll down for updated code.
There is no way of achieving this without using external libraries. However, the closest you can achieve is this:
#include <iostream>
#include <Windows.h>
#include <conio.h>
// Positions the cursor 'home'. Visually clears the screen. Using this to avoid flickering
void cls()
{
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), COORD());
}
void input(std::string& str) // Asks the user for the word
{
int char_count = 0;
while (true)
{
cls();
std::cout << "Set your Wordle first: ";
for (int i = 0; i < char_count; i++)
{
std::cout << "*";
}
if (_kbhit())
{
char c = _getch();
if (c == '\r') // The character '\r' means enter
{
return;
}
char_count++;
str.push_back(c);
}
}
}
int main()
{
char a[5]{};
std::string str;
input(str);
for (int x = 0; x < 5; x++) // Constrain to 5 characters
{
if (x < str.size()) a[x] = str[x];
else break;
}
std::cout << std::endl; // Debug start
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
{
std::cout << a[i];
} // Debug end
}
This code works as you wanted. You may see the mouse flickering but as I said, there is no proper way to do this in C++. Also, this is not the complete wordle game, and the code between // Debug start and // Debug end is just for testing purposes.
Edit: I played around with it and fixed the blinking issue:
#include <iostream>
#include <Windows.h>
#include <conio.h>
int prev_char_count = 0;
// Positions the cursor 'home'. Visually clears the screen. Using this to avoid flickering
void cls()
{
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), COORD());
}
void input(std::string& str) // Asks the user for the word
{
int char_count = 0;
cls();
std::cout << "Set your Wordle first: ";
for (int i = 0; i < char_count; i++)
{
std::cout << "*";
}
while (true)
{
if (_kbhit())
{
cls();
std::cout << "Set your Wordle first: ";
char c = _getch();
if (c == '\r') // The character '\r' means enter
{
return;
}
char_count++;
str.push_back(c);
for (int i = 0; i < char_count; i++)
{
std::cout << "*";
}
}
}
}
int main()
{
char a[5]{};
std::string str;
input(str);
for (int x = 0; x < 5; x++) // Constrain to 5 characters
{
if (x < str.size()) a[x] = str[x];
else break;
}
std::cout << std::endl; // Debug start
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
{
std::cout << a[i];
} // Debug end
}

C++ - Decrypting a string from file

As you can see from the title I need to decrypt the strings in a text file. I have major problems with this so if you can help me I would really appreciate it.
First of all, here is the input file:
saoreecessinntfi
pmrrj ie2
borj
I want to decrypt these words like this:
sesnaestocifreni
primjer 2
broj
I have used the matrix 4x4 to do this, and here is the code so far:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream test;
test.open("test.txt");
char word[5][5];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
test >> word[i][j];
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cout << word[j][i];
}
}
return 0;
}
Here is the output:
sesnaestocifreni
It only outputs the first word in text file. I think the problem with this is that I do not know how "long" is "i" and "j" in those other words beacuse the first word has 16 charachters so the counter "i" and "j" are set on 4. How to count each words charachters and if they are the same then decrpyt the word. Also if the word is right spelled I need to cout in the program "ERROR". For example
apple
I do not need to decrypt this word, beacuse it is right word, and "i" and "j" would not be the same or I do not know what I am talking about.
I think this should work just the fine for your case:
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
int matrixSize(std::string &str) {
auto x = sqrt(str.length());
return x - floor(x) == 0 ? x : 0;
}
int main() {
std::fstream file("test.txt");
std::string str;
while (std::getline(file, str)) {
if (int n = matrixSize(str)) {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
std::cout << str.at(j * n + i);
std::cout << std::endl;
} else
std::cout << "ERROR" << std::endl;
}
return 0;
}
Sample test.txt file:
saoreecessinntfi
pmrrj ie2
borj
apple
Output on test run:
sesnaestocifreni
primjer 2
broj
ERROR
If I understand your problem correctly, you are given a line of n*n characters and need to unscramble it as given.
while (true) {
std::string line;
std::getline(cin, line);
if (line.empty())
break;
int n = 1;
while (n*n < line.size()) {
n++;
}
if (n*n != line.size()) {
std::cout << "ERROR" << std::endl;
continue;
}
std::string unscrambled;
for (int col = 0; col < n; col++)
for (int row = 0; row < n; row++)
unscrambled.append(1, line[row * n + col]);
std::cout << unscrambled << std::endl;
}

Word Search using vectors in C++

I would like assistance on how I can go about a project I was assigned in which a matrix of letters is printed and user-defined words are located in all directions on the grid and colored red using colormod.h and the matrix files he provides us with. For example, executing "a.exe hard project < 0505matrix" will print the assigned inputs of the matrix with the words "hard" and "project" in red text wherever located. I'm currently expanding on my previous project (shown below) in which one word was searched with specific coordinates to search given that returns "true" or "false" and I believe my first step would be to use nested for loops in some manner to allow the word to be searched WITHOUT the given coordinates. Any assistance would be greatly appreciated! Thank you
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
bool search(vector< vector<char> > &matr, char *word, int x, int y){
bool answer = false;
if(strlen(word) > (matr.size()-y)){
return false;
}
else{
for(int i = 0; i < strlen(word); i++){
if(word[i] == matr[x][y + i])
answer = true;
else
answer = false;
break;
}
}
return answer;
}
int main(int argc, char *argv[]){
int x, y;
string word;
cin >> x;
cin >> y;
vector< vector<char> > matr;
matr.resize(x);
for(int i = 0; i < matr.size(); i++){
matr[i].resize(y);
}
for (int i = 0; i < x; i++) {
for (int j = 0; j<y ; j++){
cin >> matr[i][j];
}
}
for(int i = 0; i < x; i++) {
for(int j = 0; j < y; j++){
cout << matr[i][j] << " ";
}
cout << endl;
}
cin >> word;
cout << word;
bool check = search(matr, argv[1], atoi(argv[2]), atoi(argv[3]));
if(check){
cout << "true" << endl;
}
else{
cout << "false" << endl;
}
}

How to remove blank from code

I have coded this program and it works fine. I get the result I want but because we are using an old system to submit it, my code is rejected because it saying that the 3 last lines generate a blank of my code. Can someone please tell me where is the problem and how I can fix it? Thank you!
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int i, row_nr;
cin >> row_nr;
if(row_nr > 1 && row_nr <= 30)
for(i = 1; i <= row_nr; i++)
{
for(int j = 0; j < row_nr; j++)
{
cout << i + j * (row_nr);
{
cout << " ";
}
}
cout << endl;
}
return 0;
}
You're outputting a space after every value, so there is going to be a space at the end of each line. You should add a check so that you don't output a space after the last value of each line. It seems like you might have intended to do this, but forgot to write the if statement.
#include <iostream>
//#include <iomanip> why?
using namespace std;
int main()
{
int row_nr;
cin >> row_nr;
if(row_nr > 1 && row_nr <= 30)
for(int i = 1; i <= row_nr; i++) //declare iterator variable in for loop statement
{
for(int j = 0; j < row_nr; j++)
{
cout << i + j * (row_nr);
if(j < row_nr - 1) //you forgot this line
{
cout << " ";
}
}
cout << '\n'; //endl flushes the buffer, unnecessary here
}
return 0;
}

how to create a pyramid using for loop in c++

Hello guys I just want to ask how can I create a triangle using c++?
Actually I have my code but I don't have an idea how to center the first asterisk in the triangle. My triangle is left align. How can I make it a pyramid?
Here's my code below.
#include<iostream>
using namespace std;
int main(){
int x,y;
char star = '*';
char space = ' p ';
int temp;
for(x=1; x <= 23; x++){
if((x%2) != 0){
for(y=1; y <= x ; y++){
cout << star;
}
cout << endl;
}
}
return 0;
}
For a triangle och height Y, then first print Y-1 spaces, followed by an asterisk and a newline. Then for the next line print Y-2 spaces, followed by three asterisks (two more than previously printed) and a newline. For the third line print Y-3 spaces followed by five asterisks (again two more than previous line) and a newline. Continue until you have printed your whole triangle.
Something like the following
int asterisks = 1;
for (int y = HEIGHT; y > 0; --y, asterisks += 2)
{
for (int s = y - 1; s >= 0; --s)
std::cout << ' ';
for (int a = 0; a < asterisks; ++a)
std::cout << '*';
std::cout << '\n';
}
To calculate the number of spaces needed to center each row use this algorithm:
numSpaces = (23 - x) / 2;
and then a for loop to apply the spaces numSpaces times.
Here is the complete code:
#include<iostream>
using namespace std;
int main(){
int x,y;
char star = '*';
char space = ' p ';
int temp;
int numSpaces = 0;
for(x=1; x <= 23; x++){
if((x%2) != 0){
numSpaces = (23 - x) / 2; // Calculate number of spaces to add
for(int i = 0; i < numSpaces; i++) // Apply the spaces
{
cout << " ";
}
for(y=1; y <= x ; y++){
cout << star;
}
cout << endl;
}
}
return 0;
}
And the output:
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
*********************
***********************
One way to do
this is to nest two inner loops, one to print spaces and one to print *(s), inside an outer
loop that steps down the screen from line to line.
#include <iostream>
using namespace std;
int main(){
int row = 5;
for(int i=0; i<row; i++){
for(int j=row; j>i; j--){
cout << " ";
}
for(int k=0; k<2*i+1; k++){
cout << "*";
}
cout << endl;
}
return 0;
}
Output:
*
***
*****
*******
*********
This code is in C#, but you can convert it in c++.
class Program
{
static void Main()
{
int n = 5; // Number of lines to print.
for(int i = 1; i<= n; i++){
//loop for print space in the order (4,3,2,1,0) i.e n-i;
for(int j= 1; j<= n-i; j++){
Console.Write(" ");
}
//loop for print * in the order (1,3,5,7,9..) i.e 2i-1;
for(int k= 1; k<= 2*i-1; k++){
Console.Write("*");
}
Console.WriteLine(); // Next Line.
}
}
}
Here's another solution that doesn't use division or if statements
#include <iostream.h>
int main() {
int height = 17, rowLength, i, j, k;
char symbol = '^';
// print a pyramid with a default height of 17
rowLength = 1;
for (i = height; i > 0; i--) { // print a newline
cout << endl;
for (j = 1; j <= i; j++) // print leading spaces
cout << " ";
for (k = 0; k < rowLength; k++) // print the symbol
cout << symbol;
rowLength = rowLength + 2; // for each row increase the number of symbols to print
}
cout << "\n\n ";
return 0;
}
Star pyramid using for loop only:-
#include <iostream>
#include <conio.h>
#include <iomanip>
using namespace std;
int main()
{
int n;
cout << "enter the number of rows of pyramid you want : ";
cin >> n;
"\n";
for (int i = 0; i <= n; ++i) {
cout << "\n";
for (int j = 0; j <= n - i; ++j) {
cout << " ";
}
for (int k = 1; k <= i; k++) {
cout << setw(3) << "*";
}
}
return 0;
}
I did that using two loops
here is my code
#include <iostream>
#include <string>
using namespace std;
int main() {
int rows, star, spaces;
int number_of_stars = 5;
int number_of_rows = number_of_stars;
string str1 = "*";
for (rows=1; rows <= number_of_rows; rows++) {
for (spaces=1; spaces <= number_of_stars; spaces++) {
if (spaces==number_of_stars)
{
cout<<str1;
str1+="**";
}
else
cout<<(" ");
}
cout<<("\n");
number_of_stars = number_of_stars - 1;
}
return 0;
}
and the result is
*
***
*****
*******
*********
Url of code on Online compiler
and you can solve it using only one loop, its simple and easy
#include <iostream>
#include <string>
using namespace std;
int main()
{
int numberOfLines=4;
string spaces=string( numberOfLines , ' ' );//this is 4 spaces
string stars="*";
while(spaces!="")
{
cout<<spaces<<stars<<endl;
spaces = spaces.substr(0, spaces.size()-1);
stars+="**";
}
}
Url of code on Online compiler
#include<iostream>
using namespace std;
int for1(int &row);//function declaration
int rows;//global variable
int main()
{
cout<<"enter the total number of rows : ";
cin>>rows;
for1(rows);//function calling
cout<<"just apply a space at the end of the asteric and volla ";
}
int for1(int &row)//function definition
{
for(int x=1;x<=row;x++)//for loop for the lines
{
for(int y=row;y>=x;y--) //for loop for spaces (dynamic loop)
{
cout<<" ";
}
for(int k=1;k<=x*2-x;k++)//for loop for asteric
{
cout<<"* ";/*apply a space and you can turn a reverse right angle triangle into a pyramid */
}
cout<<endl;
}
}