I want to cout an array as a row vector but when I write:
int main() {
int B[3]={0};
for (int w = 0; w <2; w++) {
cout <<"B="<<" "<< B[w] << " ";
}
cout << endl;
return 0;
}
The output is B=0 B=0
But I want output to be like:
B=(0 0)
For a fixed size array of only I would probably even prefer a oneliner like this, because I can read it at first glance:
cout << "B=(" << B[0] << " " << B[1] << " " << B[2] << ")\n";
For a container B with a dynamic or very high number of elements n, you should probably do something like this:
cout << "B=(";
if(n > 0)
{
cout << B[0];
// note the iteration should start at 1, because we've already printed B[0]!
for(int i=1; i < n; i++)
cout << ", " << B[i]; //I've added a comma here, so you get output like B=(0, 1, 2)
}
cout << ")\n";
This has the advantage, that no matter what number of elements, you don't end up with trailing commas or unwanted whitespace.
I'd reccommend making a generic (template) function for the purpose of printing array/std::vector content anyways - it's really useful for debugging purposes!
int main() {
int B[3] = { 0 };
cout << "B=(";
for (int w = 0; w < 3; w++) {
cout << B[w];
if (w < 2) cout << " ";
}
cout << ")" << endl;
return 0;
}
Output should be now:
B=(0 0 0)
The simplest way to do this is:-
#include<iostream>
using namespace std;
int main()
{
int B[3]={0};
cout << "B=(";
for (int w = 0; w < 3; w++)
{
cout << B[w] << " ";
}
cout << ")" << endl;
return 0;
}
the output will be B= (0 0 0 )
You can try this one if you want:
#include <iostream>
using namespace std;
int main() {
int B[3]={0};
cout << "B=(";
for (int w = 0; w <2; w++) {
cout << B[w];
if(w != 1) cout << " ";
}
cout << ")" << endl;
cout << endl;
return 0;
}
The output is:
B=(0 0)
The line if(w != 1) checks whether you 've reached the last element of the array. In this case the last index is 1, but in general the if statement should be: if(w != n-1) where n is the size of the array.
Related
Currently I have a pre-made 6X6 matrix in a text file like this:
2 6 3 1 0 4
4 2 7 7 2 8
4 7 3 2 5 1
7 6 5 1 1 0
8 4 6 0 0 6
1 3 1 8 3 8
and I made a code that is reading from a file i have made. However I want to have user make a grid for themselves (i.e. 3X3 or 10X10). Which then writes to a text file automatically like in similar fashion and then have that read-in instead. It is a basic memory match card game, so I need to have rand() which generates equal pair so the game can be over when every pair in the grid has been found. Thank you so much for your time!
/*Here are the snippets of my code*/
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <fstream>
#include <string>
#include <numeric>
#include <limits>
using namespace std;
//global 2d vectors that are associated with the game
vector<vector<int> > game_grid;
vector<vector<int> > hidden_grid;
vector <vector<int> > guessed;
void initialize_grid() {
ifstream input_file;
input_file.open("grid.txt");
int num;
if (input_file) {
for (int i = 0; i < 6; ++i) {
vector<int> row; // game grid
vector<int> row2; // hidden grid
vector<int> row3; // guessed grid
for (int j = 0; j < 6; ++j) {
if (input_file >> num)
row.push_back(num);
row2.push_back(-1);
row3.push_back(0);
}
game_grid.push_back(row);
hidden_grid.push_back(row2);
guessed.push_back(row3);
}
cout << "Get is ready, Challenger!" << endl << endl;
}
else {
cout << "Womp. File open failed!";
}
return;
}
void print_grid() {
cout << "Game grid" << endl;
cout << " -------------------------" << endl;
for (int i = 0; i < 6; ++i) {
cout << " | ";
for (int j = 0; j < 6; ++j) {
cout << game_grid[i][j] << " | ";
}
cout << endl << " -------------------------" << endl;
}
cout << endl;
}
void print_hidden_grid(int r1 = -1, int r2 = -1, int c1 = -1, int c2 = -1) {
cout << "Attempt:" << endl;
if (r1 != -1) {
hidden_grid[r1][c1] = game_grid[r1][c1];
}
if (r2 != -1) {
hidden_grid[r2][c2] = game_grid[r2][c2];
}
for (int i = 0; i < 6; ++i) {
cout << " | ";
for (int j = 0; j < 6; ++j) {
if (hidden_grid[i][j] > -1)
cout << hidden_grid[i][j] << " | ";
else
cout << " | ";
}
cout << endl << " -------------------------" << endl;
}
cout << endl;
if (r1 != -1) {
if (game_grid[r1][c1] == game_grid[r2][c2]) {
guessed[r1][c1] = 1;
guessed[r2][c2] = 1;
cout << "You have a match!" << endl << endl;
}
else {
hidden_grid[r1][c1] = -1;
hidden_grid[r2][c2] = -1;
}
}
cout << endl << endl;
}
void print_current_grid() {
cout << "Current Grid:" << endl;
cout << " -------------------------" << endl;
for (int i = 0; i < 6; ++i) {
cout << " | ";
for (int j = 0; j < 6; ++j) {
if (hidden_grid[i][j] > -1)
cout << hidden_grid[i][j] << " | ";
else
cout << " | ";
}
cout << endl << " -------------------------" << endl;
}
cout << endl << endl;
}
.......
If I well understand you want to auto detect the size of the matrix when you read it ? If yes you can do something like that in initialize_grid :
void initialize_grid() {
ifstream input_file;
input_file.open("grid.txt");
int num;
if (input_file) {
// detect size
int size = 0;
string line;
if (!getline(input_file, line))
return;
istringstream iss(line);
while (iss >> num)
size += 1;
input_file.clear();
input_file.seekg(0);
for (int i = 0; i < size; ++i) {
vector<int> row; // game grid
vector<int> row2; // hidden grid
vector<int> row3; // guessed grid
for (int j = 0; j < size; ++j) {
if (input_file >> num)
row.push_back(num);
row2.push_back(-1);
row3.push_back(0);
}
game_grid.push_back(row);
hidden_grid.push_back(row2);
guessed.push_back(row3);
}
cout << "Get is ready, Challenger!" << endl << endl;
}
else {
cout << "Womp. File open failed!";
}
}
and else where you replace 6 by game_grid.size() (using size_t rather than int to type the indexes)
FizzBuzz program. The user enters numbers separated by a comma. The program reads input and lets the computer know if divisible by 3, 5 or both. When the user enters 15,5,30, the program will only output the first number, 15 and stops there. What am I doing wrong?
void processVector(vector<int> intVector)
{
bool loop;
for (int i = 0; i < intVector.size(); i++)
{
loop = true;
}
}
int main()
{
cout << "Welcome to the FizzBuzz program!" << endl;
cout << "This program will check if the number you enter is divisable by
3, 5, or both." << endl;
cout << "Please enter an array of numbers separated by a comma like so,
5,10,15" << endl;
cin >> userArray;
vector<int> loadVector(string inputString);
istringstream iss(userArray);
vector <int> v;
int i;
while (iss >> i);
{
v.push_back(i);
if (iss.peek() == ',')
iss.ignore();
if (i % 15 == 0)
{
cout << "Number " << i << " - FizzBuzz!" << endl;
}
else if (i % 3 == 0)
{
cout << "Number " << i << " Fizz!" << endl;
}
else if (i % 5 == 0)
{
cout << "Number " << i << " Buzz!" << endl;
}
else
{
cout << "Number entered is not divisable by 3 or 5." << endl;
}
}
system("pause");
}
Here is how I would approach the problem:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::cout << "!!!Hello World!!!" << std::endl; // prints !!!Hello World!!!
std::cout << "Please enter your numbers seperated by a comma (5, 3, 5, 98, 278, 42): ";
std::string userString;
std::getline(std::cin, userString);
std::vector<int> numberV;
size_t j = 0; // beginning of number
for(size_t i = 0; i < userString.size(); i++){
if((userString[i] == ',') || (i == userString.size() -1)){ // could also use strncmp
numberV.push_back(std::stoi(userString.substr(j, i))); // stoi stands for string to int, and .substr(start, end) creates a new string at the start location and ending at the end location
j = i + 1;
}
}
for(size_t n = 0; n < numberV.size(); n++){
std::cout << numberV[n] << std::endl;
}
return(0);
}
This should give you a method to solve the problem (without handling the fizzbuzz part of your program) that I personally find simpler.
The basic form for using functions is:
<return type> <function_name(<inputs)>{
stuff
};
So, a basic function that takes a string and returns a vector (what you are wanting) would be:
std::vector myStringToVector(std::string inputString){
std::vector V;
// your code (see the prior example for one method of doing this)
return(V);
};
It also looks like they want a separate function for outputting your vector values, this could look something like:
void myVectorPrint(std::vector inputVector){
// your code (see prior example for a method of printing out a vector)
};
Thank you #Aaron for the help. Here is the finished code and it works great!
I had to take a little more time researching a few things and trying to understand which order and what to put where in terms of the functions and how to call them. I appreciate all the help as I said I am a noob.
#include "stdafx.h"
#include <iostream>
#include<sstream>
#include<string>
#include<vector>
using namespace std;
vector<int> loadVector(string inputString)
{
stringstream ss(inputString);
vector <int> numberV;
int n;
size_t j = 0; // beginning of number
for (size_t n = 0; n < inputString.size(); n++)
{
if ((inputString[n] == ',') || (n == inputString.size() - 1))
{
numberV.push_back(std::stoi(inputString.substr(j, n)));
j = n + 1;
}
}
return numberV;
}
void processVector(vector<int> intVector)
{
for (int i = 0; i < intVector.size(); i++)
{
int n = intVector.at(i);
if (n % 15 == 0)
{
cout << "Number " << n << " - FizzBuzz!" << endl;
}
else if (n % 3 == 0)
{
cout << "Number " << n << " Fizz!" << endl;
}
else if (n % 5 == 0)
{
cout << "Number " << n << " Buzz!" << endl;
}
else
{
cout << "Number entered is not divisable by 3 or 5." << endl;
}
}
}
int main()
{
cout << "Welcome to the FizzBuzz program." << endl
<< "Please enter an array of numbers separated by comma's (5, 10, 15)"
<< endl;
string inputString;
getline(cin, inputString);
try
{
vector<int> intVector = loadVector(inputString);
processVector(intVector);
}
catch (const exception& e)
{
cout << "Exception caught: '" << e.what() << "'!;" << endl;
}
system("pause");
return 0;
}
I'm trying to do some of my C++ homework, but I seem to have run into an issue. I need to make it so that the user inputs 8 numbers, and those said 8 get stored in an array. Then, if one of the numbers is greater than 21, to output said number. The code is below, and it's kind of sloppy. Yes, first year C++ learner here :p
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
// Determine sum
sumVal = 0;
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Don't reinvent the wheel, use standard algorithms:
std::copy_if(std::begin(userVals), std::end(userVals),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
I improved the rest of your program as well:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
auto constexpr count = 8;
int main() {
std::vector<int> numbers(count);
std::cout << "Enter " << count << " integer values...\n";
std::copy_n(std::istream_iterator<int>(std::cin), numbers.size(), numbers.begin());
std::copy_if(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
auto sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum: " << sum << '\n';
return 0;
}
See it live on Coliru!
Ok, I'm going to explain this to you and keep it simple. This loop
`for (int i = NUM_ELEMENTS - 1; i > 21; i--)`
will never execute because in your first iteration you are checking if (NUM_ELEMENTS-1=7)>21. You are then decrementing i so this will take the series (6,5,4,...) and nothing would ever happen here.
If you have to sum the numbers greater than 21, which I presume is what you need then you will have to remove the above loop and modify your second loop to:
for (i = 0; i < NUM_ELEMENTS; i++) {
if(userVals[i]>21)
sumVal = sumVal + userVals[i];
}
This way, you add the numbers in the array that are only greater than 21. The index of userVals is determined by the i variable which also acts as a counter.
You're on the right track. There's just a few things wrong with your approach.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8;
int userVals[NUM_ELEMENTS];
int i = 0;
int sumVal = 0;
int prntSel = 0;
int size = sizeof(userVals) / sizeof(int); // Get size of your array
// 32/4 = 8 (ints are 4 bytes)
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for(int i = 0; i < size; i++) {
if(userVals[i] > 21) { // Is number > 21?
cout << userVals[i] << endl; // If so, print said number
exit(0); // And exit
}
else
sumVal += userVals[i]; // Else sum your values
}
cout << "Sum: " << sumVal << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
// for (int i = NUM_ELEMENTS - 1; i > 21; i--)
// cout << "Value: " << sumVal << endl;
for( i = 0; i < NUM_ELEMENTS; ++i )
{
if( userVals[ i ] > 21 )
{
cout << "Value: " << i << " is " << userVals[ i ] << endl;
}
}
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Try
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
to
for (i = 0; i < NUM_ELEMENTS; ++i) {
if(userVals[i] > 21)
cout << "Value: " << userVals[i] << endl;
}
This line isnt needed as well, as you arent using it.
int prntSel = 0; // For printing greater than 21
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
Here you are printing the value of sumVal, not the value of the array in the position i. The line should be:
cout << "Value: " << usersVals[i] << endl;
Also that that your for is not doing what you think it does. for doesn't use the condition you gave to decide if will execute the current iteration or not, it uses the condition to decide if the loop should continue or not. So when you put i > 21, means that it will continue running while i is bigger than 21. To achieve your goal, you should make a test (if statement) inside the loop.
The final result it would be:
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (usersVals[i] > 21) {
cout << "Value: " << usersVals[i] << endl;
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
int c;
int d;
int e;
int f;
int aa = 0;
int bb = 0;
int cc = 0;
int dd = 0;
int ee = 0;
int ff = 0;
const string odd = "ODD";
const string even = "EVEN";
cout << "enter 6 numbers " << endl;
cin >> a;
cin >> b;
cin >> c;
cin >> d;
cin >> e;
cin >> f;
aa = a % 2;
bb = b % 2;
cc = c % 2;
dd = d % 2;
ee = e % 2;
ff = f % 2;
if(aa == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
if(bb == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
if(cc == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
if(dd == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
if(ee == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
if(ff == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
return 0;
}
for example is there a way to make it do the same thing but with less code, anything I should have included?
is there an easier way than having to write 6 if/else statements - is there a way to do all 6 in one statement or loop?
how could i improve its efficiency?
Write this function:
void outputEvenness(int n)
{
static const string odd = "ODD";
static const string even = "EVEN";
if(n % 2){
cout << odd<< endl;
} else {
cout << even << endl;
}
}
then call it using outputEvenness(a); outputEvenness(b); etc.
First of all you should include header <string>if you use class std::string.
Also there is no sense to define these strings when they are used as string literals. Also instead of different variables it would be better to define only one array. The auxiliary variables are also unnecessary.
If to assume that you may not use arrays then I would write the program the following way
#include <iostream>
#include <initializer_list>
int main()
{
const size_t N = 6;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int f = 0;
const char *odd = "ODD";
const char *even = "EVEN";
std::cout << "enter " << N << " numbers: ";
std::cin >> a >> b >> c >> d >> e >> f;
for ( int x : { a, b, c, d, e, f } )
{
if ( x % 2 == 0 )
{
std::cout << x << " is " << even << std::endl;
}
else
{
std::cout << x << " is " << odd << std::endl;
}
}
return 0;
}
If you are allowed to use arrays then the program could look as
#include <iostream>
int main()
{
const size_t N = 6;
int a[N] = {};
const char *odd = "ODD";
const char *even = "EVEN";
std::cout << "enter " << N << " numbers: ";
for ( int &x : a ) std::cin >> x;
for ( int x : a )
{
if ( x % 2 == 0 )
{
std::cout << x << " is " << even << std::endl;
}
else
{
std::cout << x << " is " << odd << std::endl;
}
}
return 0;
}
For this simple program there is no sense to define a separate function that will check whether a number is even or odd because it is this program that is such a function.:)
Use arrays and loops:
int a[6]; // Array of 6 ints
cout << "enter 6 numbers" << endl;
// Input the 6 numbers
for (int i = 0; i < 6; i++)
{
cin >> a[i];
}
// Output the results
for (int i = 0; i < 6; i++)
{
cout << a[i] << " is " << (a[i] & 1 ? "ODD" : "EVEN") << endl;
}
int value = 0;
string response = "";
cout << "enter 6 numbers " << endl;
for(int i=0; i<6; i++)
{
cin >> value;
value % 2 == 0 ? response+="even\n" : response+="odd\n";
}
cout << response;
Hey I was wondering how I could have settings in-game which would allow the user to set the size of the 'game-board' by changing the array values. Here is the code. I know the code is messy and over the place but it is my first program.
#include "stdafx.h"
#include "iostream"
#include "string"
#include "cstdlib"
#include "ctime"
int xRan;
int choicei = 17;
int choicej = 17;
const int row = 15;
const int col = 16;
int play = 0;
void fill(char Array[row][col]);
int main()
{
int play = 0;
char Array[row][col];
srand((unsigned int)time(0));
xRan = rand() % 15 + 1;
if (play == 0)
{
std::cout << "1. To Play Treasure Hunt!" << std::endl;
std::cout << "2. How To Play Treaure Hunt!" << std::endl;
std::cout << "3. Treaure Hunt Settings! (Comming Soon)\n" << std::endl;
std::cin >> play;
std::cout << "-----------------------------------------------------------------------" << std::endl;
}
if (play == 2)
{
std::cout << "1. Select a row number. Be sure to make it less than or equal to " << row << "!" << std::endl;
std::cout << "2. Select a column number. Be sure to make it less than or equal to " << col << "!" << std::endl;
std::cout << "3. If you see the 'X' you have won! If you see the 'O' you lose!" << std::endl;
std::cout << "-----------------------------------------------------------------------\n" << std::endl;
std::cin >> play;
}
if (play == 3)
{
std::cout << "\nComming Soon!" << std::endl;
std::cout << "-----------------------------------------------------------------------\n" << std::endl;
std::cin >> play;
}
while (choicei > row || choicej > col || choicei < 1 || choicej < 1)
{
std::cout << "\nEnter The Row Number Less Than Or Equal To " << row << "!" << std::endl;
std::cin >> choicei;
std::cout << std::endl;
std::cout << "Enter The Column Number Less Than Or Equal To " << col << "!" << std::endl;
std::cin >> choicej;
std::cout << "\n-----------------------------------------------------------------------" << std::endl;
if (choicei > row || choicej > row)
{
std::cout << "Make Sure The Row And Column Numbers Are Less Than Or Equal To " << row << "and" << col << "!\n" "---------------------------------------------------------------------- - " << std::endl;
}
if (choicei < 1 || choicej < 1)
{
std::cout << "Make Sure The Row And Column Numbers Are More Than Or Equal To 1" << "!\n" "-----------------------------------------------------------------------" << std::endl;
}
}
fill(Array);
std::cout << std::endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
std::cout << Array[i][j] << " ";
}
std::cout << std::endl;
}
if (xRan > 11)
{
std::cout << "\nCongratulations! You Won!\n" << std::endl;
}
else
{
std::cout << "\nBetter Luck Next Time!\n" << std::endl;
}
}
void fill(char Array[row][col])
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
Array[i][j] = '*';
}
}
if (xRan > 11)
{
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < col; j++)
{
Array[choicei - 1][choicej - 1] = 'X';
}
}
}
else
{
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < col; j++)
{
Array[choicei - 1][choicej - 1] = 'O';
}
}
}
}
Thank you in advance.
you can't do that with ordinary arrays. you should use dynamic arrays, for example std::vector http://www.cplusplus.com/reference/vector/vector/
Actually, what you want to do can be done in C, not in C++: C++ requires array dimensions to be compile time constants, C can use any runtime value.
If you stay in C++, you should take a look at vector<>. If, however, you choose to use C you can simply remove the const from the declaration of row and col.
You may find this answer useful. It lists several methods to create dynamic arrays.
Quoting the answer :
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard)
Based on the suggestions, here are some ways you could initialize it (ignoring how you take the input value) :-
vector<vector<char>> Array(row, vector<char>(col));
or
char **Array = new char*[row];
for(int i = 0; i < row; i++)
{
Array[i] = new char[col];
}
UPDATE
Based on the comments, I am adding how to use the vector method and use it with the function 'fill'. fill uses reference while fill_with_ptr makes use of pointer. Although I list both the methods, I strongly recommend the one using reference.
void fill(vector<vector<char> >& array);
void fill_with_ptr(vector<vector<char> >* array);
int main()
{
...
cin >> row;
cin >> col;
vector<vector<char> > Array(row, vector<char>(col));
...
fill (Array); // or fill_with_ptr(&Array);
}
void fill(vector<vector<char> >& array)
{
... // access elements as array[i][j]
}
void fill_with_ptr(vector<vector<char> >* array)
{
... // access elements as (*array)[i][j]
}