Why is the array not printing out here? (c++) - c++

The array I have is
int age[5] = {11,2,23,4,15}
but it does not print out 11,2,23,4, 15.
#include <iostream>
#include <array>
using namespace std;
int main() {
int age[5] = {11,2,23,4,15};
cout << age[5] << endl;
}

The name of the array is not age[5].
The name of the array is age.
The expression age[5] represents the array's sixth element, which does not exist.
In fact, there is no built-in logic for printing a whole array in a formatted manner, so even cout << age << endl is not correct.
If you want to print the array, do it element-by-element in a loop.

Arrays are 0-indexed. In your example, the valid indexes are 0..4. You are trying to print a single int from age[5], which is out of bounds.
You need to loop through the indexes of the array, eg:
#include <iostream>
using namespace std;
int main() {
int age[5] = {11,2,23,4,15};
for(int i = 0; i < 5; ++i) {
cout << age[i] << " ";
}
cout << endl;
}
Alternatively:
#include <iostream>
#include <array>
using namespace std;
int main() {
array<int, 5> age{11,2,23,4,15};
for(int val : age) {
cout << val << " ";
}
cout << endl;
}

Related

How to convert a string into the sum of ASCII values?

I am a beginner and taking a CSC course, I have to write a program that converts a user input string into the sum of the ASCII value of each character, here is what I have so far, and Im still pretty far from being done. But any help would be greatly appreciated. Thanks
#include <iostream>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
using std::string;
using std::cout;
using std::endl;
int main()
{
{
int x;
std::cout << "enter string" << std::endl;
std::cin >> x;
}
string text = "STRING";
for (int i = 0; i < text.size(); i++)
cout << (int)text[i] << endl;
return 0;
}
You can use a range-based for loop to traverse the string and then add up each char within:
#include <iostream>
#include <string>
int main()
{
int sum = 0; // this is where all the values are being added to
std::string s;
std::cout << "enter string and press enter." << std::endl;
std::cin >> s; // string that the user enters will be stored in s
for (char c : s)
sum += c;
std::cout << "total ASCII values: " << sum << std::endl;
return 0;
}

How to make an array in a function in C++?

What I'm trying to output is the dealer's roll (the numbers are supposed to be stored in an array) but I keep getting an error that int is an invalid type in DealerRoll(dealerRoll[3]);
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//Dice Rolls
int DealerRoll(int dealerRoll[3]) {
srand (time(NULL));
for (int dealerCount = 0; dealerCount < 3; dealerCount++) {
dealerRoll[dealerCount] = rand()% 6+1;
cout << dealerRoll[dealerCount] << " ";
}
return dealerRoll[3];
}
int main() {
int dealerRoll;
cout << "Dealer's Roll: " << endl;
DealerRoll(dealerRoll[3]);
system ("pause");
return 0;
}
Although you can make an array in a function, std::vector provides better flexibility, and deals with resource management for you.
If array size is fixed, you can use std::array<int,3> instead:
void DealerRoll(std::array<int,3>& dealerRoll) {
srand (time(NULL));
for (int dealerCount = 0; dealerCount < 3; dealerCount++) {
dealerRoll[dealerCount] = rand()% 6+1;
cout << dealerRoll[dealerCount] << " ";
}
}
...
int main() {
std::array<int,3> dealerRoll;
cout << "Dealer's Roll: " << endl;
DealerRoll(dealerRoll);
...
}
Change the line int dealerRoll; as int dealerRoll[3];
Reason: You need to pass the array to function but you are declaring the integer variable.
Change the line DealerRoll(dealerRoll[3]); as DealerRoll(dealerRoll);
Reason: Function takes array as input but you have passed the 3rd position of array(Which will decompose to integer) instead of array.
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//Dice Rolls
void DealerRoll(int* dealerRoll) //retrieving array in pointer
{
srand (time(NULL));
for (int dealerCount = 0; dealerCount < 3; dealerCount++)
{
dealerRoll[dealerCount] = rand()% 6+1;
cout << dealerRoll[dealerCount] << " ";
}
}
int main()
{
int dealerRoll[3]; //syntax for creating array
cout << "Dealer's Roll: " << endl;
DealerRoll(dealerRoll); //passing address of array in function
//As Values are passed by address, values retained in array
cout<<"\nValues in Dealer's Roll : "<<endl;
for (int dealerCount = 0; dealerCount < 3; dealerCount++)
{
cout << dealerRoll[dealerCount] << " ";
}
system ("pause");
return 0;
}

C++ input loop gives "Process finished with exit code 11" Error

The following is the start of my C++ code. I'd like to be able to type in 5 inputs and get them stored in the vector. However the code breaks on the double array element access. How can I fix this and why is it breaking? The error I'm getting on my IDE (CLion) is "could not find operator[]".
#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::setprecision;
using std::sort;
using std::streamsize;
using std::string;
using std::vector;
int main () {
vector<int> inputVec;
int x;
while (cin >> x && inputVec.size() < 5) {
inputVec.push_back(x);
cout << inputVec.size() << endl;
}
sort(inputVec.begin(), inputVec.end());
cout << "before if 1" << endl;
typedef vector<double>::size_type vec_sz;
vec_sz size = inputVec.size();
cout << "before if 3" << endl;
if (size < 4) {
cout << "too few inputs";
} else {
cout << "calculating quartiles" << endl;
int quartileSize = size / 4;
int leftOvers = size - quartileSize * 4;
int count = 0;
vector<vector<int>> quartiles(4);
for (int i = 0; i < 3; i++) {
for (int j = 0; i < quartileSize; j++) {
quartiles[i][j] = inputVec[count++];
}
}

C++ How can I shuffle a vector without using the shuffle functions from the standard library?

For some odd reason, I have an assignment to shuffle the contents of a vector without using the shuffle or random_shuffle functions that are available in the C++ standard library. The following is some basic code with a (non-functioning) function to do the job to give you a clearer idea of what I'm getting at:
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
// Shuffle Vector Function:
void shuffle_vector(std::vector<string> &names)
{
}
// end function
int main(void)
{
srand(time(0));
vector<string> names;
names.push_back("Sally");
names.push_back("Sue");
names.push_back("Bob");
names.push_back("Fred");
cout << "Your names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cout << "Press Enter to shuffle.";
cin.get();
shuffle_vector(names);
cout << "\nYour shuffled names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cin.get();
}
The way I thought to do it is to:
"push_back" the vector to create a temporary spot
randomly assign an index into the temporary spot
randomly assign an index into the newly-empty spot
put the index in the temporary spot into the last remaining empty index
"pop_back" the vector to its original size
(like with switching indexes in arrays)
I don't know how exactly to execute this but also--more importantly--if this would even work or if it's the best way to go about it. How would you do it?
Bam! This was actually pretty fun to figure out!
I used rand and a "for" loop that iterated 100 times to randomize it. I also added a "temporary" index that was deleted after the shuffling was complete.
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
// Shuffle Vector Function:
void shuffle_vector(std::vector<string> &names)
{
for (int i = 0; i < 100; i++)
{
int randomIndex = rand() % names.size();
int randomIndex2 = rand() % names.size();
if (randomIndex2 == randomIndex) // make sure the two random values aren't the same
{
do {
randomIndex2 = rand() % names.size();
} while (randomIndex2 == randomIndex);
}
names.push_back("temporary"); // create temporary index at the end of the vector
int last_index_number = (names.size() - 1);
names[last_index_number] = names[randomIndex];
names[randomIndex] = names[randomIndex2];
names[randomIndex2] = names[last_index_number];
names.pop_back(); // bring vector back to original size
}
}
// end function
int main(void)
{
srand(time(0));
vector<string> names;
names.push_back("Sally");
names.push_back("Sue");
names.push_back("Bob");
names.push_back("Fred");
cout << "Your names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cout << "Press Enter to shuffle.";
cin.get();
shuffle_vector(names);
cout << "\nYour shuffled names:" << endl;
for (int i = 0; i < names.size(); i++)
{
cout << i + 1 << ". " << names[i] << endl;
}
cin.get();
}

Displaying contents of a vector container in C++

The following is a C++ program using STL vector container. Just wanted to know why the display() function is not printing the vector contents to the screen. If displaying the size() line is commented out, display() function works fine.
#include <iostream>
#include <vector>
using namespace std;
void display(vector<int> &v)
{
for(int i; i<v.size(); i++)
{
cout << v[i] << " ";
}
cout << "\n" << endl;
}
int main()
{
vector<int> v;
cout << "Size of Vector=" << v.size() << endl;
//Putting values into the vector
int x;
cout << "Enter five integer values" << endl;
for(int i; i<5; i++)
{
cin >> x;
v.push_back(x);
}
//Size after adding values
cout << "Size of Vector=" << v.size() << endl;
//Display the contents of vector
display(v);
v.push_back(6);
//Size after adding values
cout << "Size of Vector=" << v.size() << endl;
//Display the contents of vector
display(v);
}
Output:
Size of Vector=0
Enter five integer values
1
2
3
4
5
Size of Vector=5
Size of Vector=6
There is an idiomatic way for printing a vector out.
#include <algorithm>
#include <iterator>
//note the const
void display_vector(const vector<int> &v)
{
std::copy(v.begin(), v.end(),
std::ostream_iterator<int>(std::cout, " "));
}
This way is safe and doesn't require you to keep track of the vectors size or anything like that. It is also easily recognisable to other C++ developers.
This method works on other container types too that do not allow random access.
std::list<int> l;
//use l
std::copy(l.begin(), l.end(),
std::ostream_iterator<int>(std::cout, " "));
This works both ways with input too consider the following:
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
std::cout << "Enter int end with q" << std::endl;
std::vector<int> v; //a deque is probably better TBH
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter<int>(v));
std::copy(v.begin(), v.end(),
std::ostream_iterator<int>(std::cout, " "));
}
This version doesn't require any hard coding of size or manual management of the actual elements.
You are not initializing your variables. for(int i = 0; not for(int i;
I think this is the easiest way to go:
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> v;
int x;
cout << "Enter five integer values" << endl;
for(int i=0; i<5; i++)
{
cin >> x;
v.push_back(x);
}
for (int i = 0; i < (int)v.size(); i++)
cout<< v.at(i) <<endl;
}
If you use compiler versions g++ 11 or more than then you simply use:
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> v;
int x;
cout << "Enter five integer values" << endl;
for(int i=0; i<5; i++)
{
cin >> x;
v.push_back(x);
}
for (auto i: v)
cout<< i <<endl;
}
I have found printing using for_each() very easy to understand and intuitive
#include<vector>
#include<algorithm>
using namespace std;
main(){
vector<int> foo_bar{1,2,3,4,5};
auto print_array = [](const auto& o) {cout << o << " "; };
for_each(foo_bar.begin(), foo_bar.end(), print_array);
}