I've just started learning C++ and decided to give myself a challenge by creating a simple Christmas Tree program. Everything has been working so far although the code doesn't produce what I expect. I've spent a decent amount of time trying to figure out what's wrong but can't seem to figure out why it doesn't work.
So far, the code looks like this:
#include <iostream>
#include <string>
int main(){
char cTree;
int iSize, iSpace;
std::cout << "Christmas Tree Application" << std::endl;
std::cout << "Enter the size of your christmas tree: ";
std::cin >> iSize;
std::cout << "Enter the character you would like to use for your tree: ";
std::cin >> cTree;
iSpace = iSize / 2;
for(int i = 0; i < iSize; i++){
std::string sTree(i, cTree);
//std::string sSpace(iSpace, ' ');
std::cout << sTree << std::endl;
//iSpace -= 1;
}
return 0;
}
I've also commented out the 'spacing' part because whenever I execute it, it creates an error that I have no clue why it is says that. I know I can do the spacings in a different manner but I'd like to use the std::string way. Any help?
iSpace is set to iSize / 2, yet you run the loop iSize times, decreasing iSpace by one every time. Eventually, iSpace will be negative, which is why you have the error. Try this:
iSpace = iSize;
for(int i = 0; i < iSize; i++){
std::string sTree(i, cTree);
std::string sSpace(iSpace, ' ');
std::cout << sSpace << sTree << sTree << std::endl;
iSpace -= 1;
}
You are looping on the wrong value for iSpace, as it remains constant throughout execution rather than changing like a variable does.
Also, your code can be tidied up a bit. I've posted the updated code below. I've deliberately replaced spaces with underscore characters to provide a better graphical representation of my logic.
Good luck!
Code Listing
#include <iostream>
#include <string>
using namespace std;
int main(void) {
char cTree;
int iSize;
int iSpace;
int iChars;
cout << "Christmas Tree Application" << endl;
cout << "Enter the height of your christmas tree: ";
cin >> iSize;
cout << "Enter the character you would like to use for your tree: ";
cin >> cTree;
for(int i = 0; i < iSize; i++){
iSpace = (iSize-i)-1;
iChars = (2*i)+1;
string sSpace(iSpace, '_');
string sTree(iChars, cTree);
cout << sSpace << sTree << sSpace << endl;
}
return 0;
}
Sample Run
Christmas Tree Application
Enter the height of your christmas tree: 10
Enter the character you would like to use for your tree: #
_________#_________
________###________
_______#####_______
______#######______
_____#########_____
____###########____
___#############___
__###############__
_#################_
###################
awesomeyi is right about the error, however if you'd like it to look more "tree-like" you'll need to double your loop.
i.e.
#include <iostream>
#include <string>
int main(){
char cTree;
int iSize, iSpace;
std::cout << "Christmas Tree Application" << std::endl;
std::cout << "Enter the size of your christmas tree: ";
std::cin >> iSize;
std::cout << "Enter the character you would like to use for your tree: ";
std::cin >> cTree;
iSpace = iSize;
for (int i = 0; i < iSize*2; i+=2){
std::string sTree(i, cTree);
std::string sSpace(iSpace, ' ');
std::cout << sSpace + sTree + sSpace<< std::endl;
iSpace -= 1;
}
return 0;
}
Just for fun, here's a recursive implementation:
#include <iostream>
#include <string>
#include <cstdio>
void drawTree(int level, int height, char c) {
if(level > 0)
drawTree(level-1, height, c);
std::cout << std::string(height-level, ' ') << std::string((2*level)+1, c) << std::endl;
}
int main(){
char cTree;
int iSize;
std::cout << "Christmas Tree Application" << std::endl;
std::cout << "Enter the size of your christmas tree: ";
std::cin >> iSize;
std::cout << "Enter the character you would like to use for your tree: ";
std::cin >> cTree;
drawTree(iSize, iSize, cTree);
return 0;
}
Related
I'm working on a program that I've seen other people do online except I'm trying to use functions to complete it to make it somewhat more challenging for me to help me better understand pointers and vectors. The problem I'm having in xcode is I keep getting this error..
Expected ';' after top level declarator
right here on my code,
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers) //<<< Error
{
cout << fixed << setprecision(2);
...
Where I am trying to use vector numbers in my function. Basically I want the numbers from the function passed back so that I can use them in another function I have not created yet. I've googled this error and it seems like no one can give a straight answer on how to fix this problem. Is anyone familiar with how to correct this? By no means is this code finished I'm just trying to get information regarding vectors as a parameter because from what I'm seeing syntax wise on other sites it looks to be correct. Thanks for your feedback.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
#include <iterator>
using namespace std;
struct menuItemType{
string menuItem;
double menuPrice;
};
void getData(menuItemType (&mlist)[8]);
void showMenu(menuItemType (&menu_List)[8], vector<int> numbers);
int main() {
vector<int> temp;
menuItemType menuList[8];
getData(menuList);
showMenu(menuList,temp);
/*
cout << menuList[0].menuItem << " " << menuList[0].menuPrice << endl;
cout << menuList[1].menuItem << " " << menuList[1].menuPrice << endl;
*/
return 0;
}
void getData(menuItemType (&mlist)[8]){
string Str;
ifstream infile;
infile.open("cafe135.txt");
if(infile.is_open())
{
for (int i = 0; i < 8; ++i){
infile >> mlist[i].menuItem >> mlist[i].menuPrice;
}
}
else cout << "Unable to open file";
}
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers)
{
cout << fixed << setprecision(2);
string choice;
cout << "Would you like to view the menu? [Y] or [N]: ";
cin >> choice;
cout << endl;
int x = 3;
int count = 1;
while (choice != "Y" && choice != "N" && choice != "y" && choice != "n")
{
if (count == 4){
return;
}
cout << "Error! Please try again ["
<< x
<< "] selections remaining: ";
cin >> choice;
cout << endl;
x--;
count++;
}
if (choice == "N" || choice == "n"){
return;
}
else
{
cout << "___________ Breakfast Menu ___________" << endl;
for (int i = 0; i < sizeof(menu_List)/sizeof(menu_List[0]); ++i)
{
cout << "Item "
<< (i+1)
<< ": "
<< menu_List[i].menuItem
<< " "
<< menu_List[i].menuPrice
<< endl;
}
cout << endl;
string itemSelection = " ";
//int str_length = 0;
cout << "Select your item numbers separated"
<< " by spaces (e.g. 1 3 5) Select 0 to cancel order: ";
cin.ignore();
getline(cin, itemSelection);
if (itemSelection == "0")
{
return;
}
vector<int> vectorItemSelection;
stringstream text_stream(itemSelection);
string item;
while (getline(text_stream, item, ' '))
{
vectorItemSelection.push_back(stoi(item));
}
int n = vectorItemSelection.size();
int arr[n];
for (int i = 0; i < n; i++)
{
arr[i] = vectorItemSelection[i];
}
}
}
Compare how menu_List is declared in this line
void showMenu(menuItemType (&menu_List)[8], vector<int> numbers);
and this line
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers)
The first one is correct.
But I have to agree with the comments above, you are mixing up a lot of different things here. Just use vectors, 99% of the time it's the right thing to do anyway. and it's easier to learn one thing at a time.
Prefer to write your code like this
void getData(vector<menuItemType>&);
void showMenu(vector<menuItemType>&, vector<int> numbers);
int main() {
vector<int> temp;
vector<menuItemType> menuList(8);
...
See? Just use vectors everywhere.
I want to store the elements of struct into a text file. I have multiple inputs and this is what I have done, however, I can only store the latest inputs but not all the input. Thanks in advance for the help! Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
struct ProcessRecords {
string ID;
int arrival;
int wait;
int burst;
void putToFile() {
ofstream input;
input.open ("process.txt");
input << ID << "\t" << arrival << "\t" << wait << "\t" << burst << endl;
input.close();
}
};
int main() {
int numProcess;
int algo;
cout << "\n\t\t=== CPU SCHEDULING ALGORITHMS ===\n";
cout << "\n\t\tEnter number of processes: ";
cin >> numProcess;
ProcessRecords process[numProcess];
string processID[numProcess];
int arrTime[numProcess];
int waitTime[numProcess];
int burstTime[numProcess];
cout << endl << endl;
for (int i = 0; i < numProcess; i++) {
cout << "\n\tEnter process ID for Process " << i+1 << ":\t ";
cin >> processID[i];
process[i].ID = processID[i];
cout << "\n\t\tEnter arrival time for " << processID[i] << ":\t ";
cin >> arrTime[i];
process[i].arrival = arrTime[i];
cout << "\n\t\tEnter waiting time for " << processID[i] << ":\t ";
cin >> waitTime[i];
process[i].wait = waitTime[i];
cout << "\n\t\tEnter burst time for " << processID[i] << ":\t ";
cin >> burstTime[i];
process[i].burst = burstTime[i];
process[i].putToFile();
}
return 0;
}
Here is my sample output:
First In C++(by C++ i mean standard C++ and not extensions), the size of an array must be a compile time constant. So you cannot write code like:
int n = 10;
int arr[n]; //incorrect
Correct way to write this would be:
const int n = 10;
int arr[n]; //correct
For the same reason the following statement is incorrect in your code :
int arrTime[numProcess]; //incorrect because size of array must be fixed and decide at compile time
Second you should append to the text file instead of overwriting it. For opening the file in append mode you can use:
input.open("process.txt", ofstream::app);
You can check here that the program works(append) as you desire, using input.open("process.txt", ofstream::app); . Also do note what i said about the size of array being compile time constant. I have not changed it in the link i have given. You can use std::vector for variable size container.
forum!
I have a project where we are supposed to add numbers that are length 14 or greater. I did some digging and realized that there is no current type that takes numbers this big. So, I have the user enter the numbers as a string and the numbers they would like to add are stored in a static string array.
I would like to add the numbers from the static array together. The issue is I have no idea how to deal with numbers this large. I am assuming you would have to convert the string values into int's and add them up one by one? I am having a big issue coming up with the logic for this. Any help would be appreciated.
If not, if you can provide some context which could help me come up with some logic.
The only library functions I can use is iostream and string.
Here is my code if you'll like to see my logic! I have some test cases I am trying to figure out so please ignore the comment outs. But, if you run the code you should get a better sense of what I am trying to get out. I am trying to sum up the numbers the user enters.
#include <iostream>
#include <string>
using namespace std;
void amountOfNumbers(string &userAmount, int MIN_AMOUNT, int MAX_AMOUNT){
//string alpha = "abcdefghijklmnopqrstuvwxyz";
cout << "How many numbers? -> ";
cin >> userAmount;
cout << endl;
while(!userAmount.find("abcdefghijklmnopqrstuvwxyz")){
cout << "ERROR: must be a number, try again ->";
cout << userAmount;
//cin.clear();
//cin.ignore(1000, '\n');
cin >> userAmount;
cout << endl;
}
int temp = stoi(userAmount);
while((temp < MIN_AMOUNT) or (temp > MAX_AMOUNT)){
cout << "ERROR: Program can only take in " << MIN_AMOUNT << " - "<< MAX_AMOUNT << " numbers. Try again ->";
cin >> userAmount;
cout << endl;
temp = stoi(userAmount);
}
}
void takeNumbers(string &userAmount, string (&numberArray)[11]){
int temp = stoi(userAmount);
for (int i = 0; i < temp; i++){
cout << "Input number #" << i+1 << " ->";
cin >> numberArray[i];
cout << endl;
}
}
void display(string &userAmount, string (&numberArray)[11]){
int temp = stoi(userAmount);
for (int i = 0; i < temp; i++){
cout << numberArray[i];
cout << endl;
}
}
void addNumber(string &userAmount, string (&numberArray)[11]){
}
int main() {
const int MIN_AMOUNT = 2, MAX_AMOUNT = 11, MAX_INPUT = 14;
string userAmount = "0";
string numberInput;
// static array
string numberArray [MAX_AMOUNT];
amountOfNumbers(userAmount, MIN_AMOUNT, MAX_AMOUNT);
takeNumbers(userAmount, numberArray);
display(userAmount, numberArray);
}
This program works EXCEPT that it does not allow a space between the first and last name. Below is an example as to what I am talking about:
Link to Picture
Can someone please help me to fix this? I believe it is in string playerName as it will not accept a space between the first and last name.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
// Structure to hold the Player Data
struct Player {
string playerName;
int playerNumber;
int pointsScored;
};
// Function Prototypes
void getPlayerInfo(Player &);
void showInfo(Player[], int);
int getTotalPoints(Player[], int);
void showHighest(Player[], int);
int main(int argc, char *argv[])
{
const int N = 12;
Player players[N];
for (int i = 0; i<N; i++) {
cout << "\nPLAYER #" << i + 1 << "\n";
cout << "---------\n";
getPlayerInfo(players[i]);
}
showInfo(players, N);
int totalPoints = getTotalPoints(players, N);
cout << "TOTAL POINTS: " << totalPoints << "\n";
cout << "The player who scored the most points is :";
showHighest(players, N);
cout << "\n";
system("pause");
return 0;
}
void getPlayerInfo(Player &P) {
cout << "Player Name:";
//cin >> P.playerName; **CHANGED THIS**
cin.ignore(std::numeric_limits<std::streamsize>::max(), ' ');
std::getline(std::cin, P.playerName); **TO THIS**
do {
cout << "Player Number:";
cin >> P.playerNumber;
if (P.playerNumber<0)
cout << "invalid Input\n";
} while (P.playerNumber<0);
do {
cout << "Points Scored:";
cin >> P.pointsScored;
if (P.pointsScored<0)
cout << "invalid Input\n";
} while (P.pointsScored<0);
}
void showInfo(Player P[], int N) {
cout << "\nNAME" << "\t\tNUMBER" << "\t\tPOINTS SCORED" << "\n";
for (int i = 0; i<N; i++)
cout << P[i].playerName << "\t\t" << P[i].playerNumber << "\t\t" << P[i].pointsScored << "\n";
}
int getTotalPoints(Player P[], int N) {
int Points = 0;
for (int i = 0; i<N; i++)
Points += (P[i].pointsScored);
return Points;
}
void showHighest(Player P[], int N) {
int HighestPoint = P[0].pointsScored;
string Name = P[0].playerName;
for (int i = 1; i<N; i++) {
if (HighestPoint<P[i].pointsScored) {
HighestPoint = P[i].pointsScored;
Name = P[i].playerName;
}
}
cout << Name;
}
When std::cin uses operator>> to insert into a std::string, it stops reading at space (' ') characters. Use std::getline instead.
std::getline(std::cin, P.playerName); //read everything up to '\n'
The problem is in this code:
void getPlayerInfo(Player &P) {
cout << "Player Name:";
cin >> P.playerName;//<<----
cin treats ' ' (space) as a delimiter. If you want to have an input with ' ' (space) you need to use: (thanks to #James Root)
//before doing get line make sure input buffer is empty
see also: https://stackoverflow.com/a/10553849/3013996
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin,P.playerName);
The program works all the way up until it checks for the name the user enters. When you enter the name you wish to search for in the array of structures that have been imported from a file full of customer info) it comes back segmentation fault core dumped. This puzzles me.
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
struct AccountsDataBase{
char name[50];
string email;
long int phone;
string address;
};
#define MAX 80
AccountsDataBase * account = new AccountsDataBase[MAX];
void readIn(ifstream& file){
int i=0;
while(!file.eof()){
file >> account[i].name >> account[i].email >> account[i].phone >> account[i].address;
}
}
void getAccount(){
char userPick[50];
char streamName[50];
cout << " What account will we be using? " << endl;
cin.getline(streamName, 50);
for(int i=0; strcmp(account[i].name, streamName)!=0; i++){
if( strcmp(account[i].name, streamName)==0){
cout << "\n\n FOUND IT!! \n\n";
cout << account[i].name << "\n" << account[i].email << "\n" << account[i].phone << "\n" << account[i].address << endl;
}
}
}
int main(){
ifstream file;
file.open("2.dat"); //opens data account records text
readIn(file);
getAccount();
delete account;
return 0;
}
Your loop keeps reading everything into the initial element of the array:
while(!file.eof()){
file >> account[i].name >> account[i].email >> account[i].phone >> account[i].address;
}
because the value of i is never incremented. You can convert this to a for loop, like this:
for (count = 0 ; count < MAX && !file.eof() ; count++) {
file >> account[count].name >> account[count].email >> account[count].phone >> account[count].address;
}
Note that I changed i to count:
AccountsDataBase * account = new AccountsDataBase[MAX];
int count = 0;
This will help you solve another problem - determining when the array ends in the getAccount function. Currently, you assume that the record is always there, so the outer loop keeps going on. Now that you have count, you could change the loop like this:
for(int i=0; i < count && strcmp(account[i].name, streamName)!=0; i++){
if( strcmp(account[i].name, streamName)==0){
cout << "\n\n FOUND IT!! \n\n";
cout << account[i].name << "\n" << account[i].email << "\n" << account[i].phone << "\n" << account[i].address << endl;
break;
}
}
if (i == count) {
cout << "Not found." << endl;
}