c++ how to use while properly [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I am learning c++ around two weeks and therefore have a lot of questions. It feels like i learn a new sport. My body in my thinking already moving much better than any other olympic players, but the actual movement is so poor.
what i want to know is if i can use "while" in cout together.
int main() {
struct {
string engineType;
string brand;
int price;
int range;
} candidate1, candidate2;
// information of candidate 1
candidate1.name = "IONIQ5";
candidate1.range = 450;
candidate1.price = 35000;
// information of candidate 2
candidate2.brand = "Tesla_Model_3";
candidate2.range = 650;
candidate2.price = 55000;
// show each price with while function
int i = 1;
while (i<3) {
cout << "Price :" << candidate[i].range << endl ;
i++;
}
return 0;
I want to have as a result of print
450
650
what do i have to do to get it ?
Thanks for the help !

Use an array and initialize it.
First you need to name your structure:
struct candidate {
std::string engineType;
std::string brand;
int price;
int range;
};
Then create and initialize the array:
std::array<candidate, 2> candidates = {
{ "Electric", "IONIQ5", 35000, 450 },
{ "Electric", "Tesla_Model_3", 55000, 650 }
};
And finally iterate over it:
for (auto const& candidate : candidates) {
std::cout << "Price: " << candidate.price << '\n';
}
All this should be well-covered in a decent book.

You can use an array with elements of type Candidate and then loop through the array and print the values as shown below:
//class representing a Candidate info
struct Candidate{
string engineType;
string brand;
int price;
int range;
};
int main() {
//create an array witht element of type Candidate;
Candidate arr[] = {{"IONIQ5", "Honda", 450, 3500}, {"Tesla_Model_3", "Tesla", 650, 55000}};
//iterate through the array using range based for loop
for(const Candidate& candidate: arr)
{
std::cout<<candidate.range<<std::endl;
}
}
Working demo

You cannot use candidate1 like candidate[i] because it works as a variable name . You need to use maps or arrays for this type of tasks.

You are declaring 2 separate variables, called candidate1 and candidate2 as an array, so candidate[i] does not resolve to anything.
You need to initialize the array as follows:
main ()
{
struct
{
string engineType;
string brand;
int price;
int range;
} candidate[3];
// information of candidate 1
candidate[1].brand = "IONIQ5";
candidate[1].range = 450;
candidate[1].price = 35000;
// information of candidate 2
candidate[2].brand = "Tesla_Model_3";
candidate[2].range = 650;
candidate[2].price = 55000;
// show each price with while function
int i = 1;
while (i < 3)
{
cout << "Price :" << candidate[i].range << endl;
i++;
}
return 0;
}
Please note that arrays start with 0, so an array of 3 will have values for postitions 0, 1, 2, hence the candidate[3], but I would recommend going with candidate[2] and setting values for positions 0 and 1.

Related

No Matching Function To Call Error, and i don't know why [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
Improve this question
I'm having an error that the function that I'm calling doesn't exist and I don't know why. It seems to have something to do with pointers but we haven't learned pointers. I call the function and wrote it and declared it (I'm mostly just typing so I can post this at this point)
Here is my code
/*
* Program to validate a color and show its index
*
* Name: Rebecca Sakson
* Date: November 13, 2022
*/
#include <iostream>
using namespace std;
const int NUM_COLORS = 5;
int findColorIndex (string findMe, string list[], int index[]);
int main()
{
string colors[NUM_COLORS] = { "red", "green", "blue", "yellow", "purple"};
int index[NUM_COLORS] = {0,1,2,3,4};
string findMe;
int colorIndex;
//int idkWhy = NUM_COLORS;
cout << "Color?" << endl;
cin >> findMe;
colorIndex = findColorIndex(findMe, colors, NUM_COLORS);
if (colorIndex <= 0)
{
cout << "Color is valid, found at " << colorIndex << endl;
}
else
{
cout << findMe << " is not valid";
}
return 0;
}
int findColorIndex (string findColor, string list[], int index[])
{
bool found = false;
int functionIndex = 0;
while ((!found) && (functionIndex < *index))
{
if (list[functionIndex] == findColor)
{
found = true;
}
else
{
functionIndex++;
}
}
if (!found)
{
functionIndex = -1;
}
return functionIndex;
}
I think you meant to type this:
findColorIndex(findMe, colors, index);
Instead of passing NUM_COLORS, which is an int, not an int array.

Calling name for passing two arrays (a string and an int) to a function in C++

I'm aware that when you write the call for your function you write it as displayArray(seasons,10)
with the name of one array and its size. I'm stuck on how you would right the arguments to pass the two arrays listed in my code, seasons and cartoons.
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
void displayArray(string car[], int sea[], int size);
int main()
{
int seasons[] = {5,10,8,2,12,7,31,9,3,4};
string cartoon[] = { "Steven Universe","Adventure Time","Regular Show","Gravity Falls",
"Spongebob Squarepants","Futurama","The Simpsons","Bob's Burgers","Avatar: The Last Airbender","Rick and Morty"};
displayArray() // Error Message here
}
void displayArray(string car[], int sea[], int size)
{
for (int x = 0; x < size; x++)
{
cout << " " << car[x] << "\t\t" << sea[x] << right << endl;
}
}
So you have to first create an array to pass your values with. Then just pass the array.
void function(int arr[]) {}
int arr[] = { 1, 2, 3, 4, 5 };
function(arr);
So in your code above, it should look like this:
int main()
{
int seasons[] = {5,10,8,2,12,7,31,9,3,4};
string cartoon[] = { "Steven Universe","Adventure Time","Regular Show","Gravity Falls",
"Spongebob Squarepants","Futurama","The Simpsons","Bob's Burgers","Avatar: The Last Airbender","Rick and Morty"};
displayArray(cartoon, seasons, 10);
}
Hope this helps :)
displayArray(cartoon, seasons, 5);
This seems to work fine for me. You just pass each array in according to whichever is declared first in the function argument list. Am I misunderstanding your question?

void class Arrays Sequential and Binary Search Using

I'm currently at my wits end trying to figure out how to do this, and was hoping someone could help.
The objectives the assignment is to:
Display the original sorted array of student records.
Display the sequential search result of student records.
Display the binary search result of student records.
The Full Instructions are:
a. Create three array of 12+ students records including ID’s, student names, and
the corresponding e-mail address’,– student ID’s are sorted in order. (No sort program needed for now.)
b. Sequential Search five ID’s which are from the sorted array and a 6th ID which is not from the array.
c. Binary Search five ID’s which are from the sorted array and a 6th ID which is not from the array.
d. Execution and output:
Display the original sorted array of student records.
Display the sequential search result of student records.
Display the binary search result of student records.
Any Help would be greatly appreciated
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
struct Student {
string name;
int stuID;
string email;
};
// Show the student information
void showAllInfo(Student *studentArray, int stuCount) {
cout << "Student Info: "<<endl <<endl<<
"\t\tStudent Name"<<"\t\tStudent ID"<<"\t\tStudent Email"<<endl<<endl ;
for (int i = 0; i < stuCount; i++)
{
cout<<"\t\t"<< studentArray[i].name<<"\t\t"<<studentArray[i].stuID<<"\t\t\t"<< studentArray[i].email<<endl;
}
cout << endl;
}
//Sort out the arrays for the student information
void firstArray()
{
Student studentArray[12];
studentArray[0].name = "Bob McBoberston";
studentArray[0].stuID = 00;
studentArray[0].email = "BMcboberts#txstate.edu";
studentArray[1].name = "Shelby Donald";
studentArray[1].stuID = 1;
studentArray[1].email = "SDonald#txstate.edu";
studentArray[2].name = "Ronald Mcdonald";
studentArray[2].stuID = 2;
studentArray[2].email = "RMcdonald#txstate.edu";
studentArray[3].name = "Dick Cheney";
studentArray[3].stuID = 3;
studentArray[3].email = "DCheney#txstate.edu";
studentArray[4].name= "Ben Dover";
studentArray[4].stuID=4;
studentArray[4].email="BDover#txstate.edu";
studentArray[5].name="Ash Katchum";
studentArray[5].stuID=5;
studentArray[5].email="AKatchum#txstate.edu";
studentArray[6].name="Brock Whatever";
studentArray[6].stuID=6;
studentArray[6].email="BWhatevr#txstate.edu";
studentArray[7].name="Yugi Oh";
studentArray[7].stuID=7;
studentArray[7].email="YugiOh#txstate.edu";
studentArray[8].name="Johnny Bravo";
studentArray[8].stuID=8;
studentArray[8].email="JBravo#txstate.edu";
studentArray[9].name="Tom N. Jerry";
studentArray[9].stuID=9;
studentArray[9].email="Tnjerry#txstate.edu";
studentArray[10].name="Fred Flinstone";
studentArray[10].stuID=10;
studentArray[10].email="FFlinstone#emial.com";
studentArray[11].name="Son Goku";
studentArray[11].stuID=11;
studentArray[11].email="sGoku#txstate.edu";
studentArray[12].name="Johnny Test";
studentArray[12].stuID=12;
studentArray[12].email="JTest#txstate.edu";
}
void secondArray()
{
Student studentArray2[12];
studentArray2[0].name = "Rick Sanchez";
studentArray2[0].stuID = 13;
studentArray2[0].email = "RSanchez#txstate.edu";
studentArray2[1].name="Morty Smith";
studentArray2[1].stuID = 14;
studentArray2[1].email = "MSmith#txstate.edu";
studentArray2[2].name = "Summer Smith";
studentArray2[2].stuID = 15;
studentArray2[2].email = "SSmith#txstate.edu";
studentArray2[3].name = "Jerry Smith";
studentArray2[3].stuID = 16;
studentArray2[3].email = "JSmith#txstate.edu";
studentArray2[4].name="Mr. Meeseeks";
studentArray2[4].stuID=17;
studentArray2[4].email="MMeeseeks#txstate.edu";
studentArray2[5].name="Mr. PoopyButtHole";
studentArray2[5].stuID=18;
studentArray2[5].email="MPoopyButt#txstate.edu";
studentArray2[6].name="Tiny Rick";
studentArray2[6].stuID=19;
studentArray2[6].email="TRick#txstate.edu";
studentArray2[7].name="Pickle Rick";
studentArray2[7].stuID=20;
studentArray2[7].email="PRick#txstate.edu";
studentArray2[8].name="Beth Smith";
studentArray2[8].stuID=21;
studentArray2[8].email="BSmith#txstate.edu";
studentArray2[9].name="Bird Person";
studentArray2[9].stuID=22;
studentArray2[9].email="BmPerson#txstate.edu";
studentArray2[10].name="Squanchy";
studentArray2[10].stuID=23;
studentArray2[10].email="Squanchy#txstate.edu";
studentArray2[11].name="King Flippy Nips";
studentArray2[11].stuID=24;
studentArray2[11].email="KFlippyNipa#txstate.edu";
studentArray2[12].name="Mr> Goldenfold";
studentArray2[12].stuID=25;
studentArray2[12].email="MGoldenfold#txstate.edu";
}
void thirdArray()
{
Student studentArray3[13];
studentArray3[0].name = "Santa Claus";
studentArray3[0].stuID = 26;
studentArray3[0].email = "SClause#txstate.edu";
studentArray3[1].name = "Jason Riha";
studentArray3[1].stuID = 27;
studentArray3[1].email = "JRiha#txstate.edu";
studentArray3[2].name = "B-Rad Cragg";
studentArray3[2].stuID = 28;
studentArray3[2].email = "BRad#txstate.edu";
studentArray3[3].name="Roger Legrand";
studentArray3[3].stuID = 29;
studentArray3[3].email = "RLegrand#txstate.edu";
studentArray3[4].name="David De La O";
studentArray3[4].stuID=30;
studentArray3[4].email= "DDelao#txstate.edu";
studentArray3[5].name="Ian Sporn";
studentArray3[5].stuID=31;
studentArray3[5].email="ISporn#txstate.edu";
studentArray3[6].name="Morgan Taylor";
studentArray3[6].stuID=32;
studentArray3[6].email="Mytaylor#txstate.edu";
studentArray3[7].name="Sam Huggins";
studentArray3[7].stuID=33;
studentArray3[7].email="SHuggins#txstate.edu";
studentArray3[8].name="Shaun Huggins";
studentArray3[8].stuID=34;
studentArray3[8].email="ShuHuggins#txstate.edu";
studentArray3[9].name="Serena Huggins";
studentArray3[9].stuID=35;
studentArray3[9].email="SerHuggins#txstate.edu";
studentArray3[10].name="Kylie Parziale";
studentArray3[10].stuID=36;
studentArray3[10].email="KParziale#txstate.edu";
studentArray3[11].name="Jimmy Fallon";
studentArray3[11].stuID=37;
studentArray3[11].email="JFallon#txstate.edu";
studentArray3[12].name="Tom Goat Brady";
studentArray3[12].stuID=38;
studentArray3[12].email="TGBrady#txstate.edu";
studentArray3[13].name="Harry Giblets";
studentArray3[13].stuID=39;
studentArray3[13].email="HGiblets#txstate.edu";
}
int main() {
int stuCount = 39;
firstArray();
secondArray();
thirdArray();
showAllInfo(studentArray,stuCount);
return 0;
}
So you have a few problems. The first is that your arrays are declared inside the functions you've written, so no other code is going to be able to access them. You should declare your arrays inside the main function so that they can be passed as parameters to other functions. If you don't know how to pass an array as a parameter then the rest of this assignment is going to be difficult for you.
Anyway lets start like this, you don't need to write function to set up your arrays, you can do it directly in main, like this
int main()
{
Student firstArray[12] = {
{ "Bob McBoberston", 0, "BMcboberts#txstate.edu" },
...
};
Student secondArray[12] = {
...
};
Student thirdArray[12] = {
...
};
...
}
Now that the arrays are set up you need to write a function to do the sequential search (binary search is more complex, so leave that one for now).
Think about what parameters a function needs and what return value it has. This is always the first step when writing a function, but it's also one that many newbies struggle with.
In the case a sequential search function it needs to know 1) which array is it going to search, 2) how big that array is, 3) what id you are searching for. These are the parameters. It seems reasonable for the function to return the index in the array of the person it's found, or a special value -1 if it doesn't find the id. That's not the only way to do it, but it'll do for now. So putting that together we have
// look for 'id' in 'array' and returns the index if found or -1 if not found
int sequential_search(Person array[], int array_size, int id)
{
...
}
In your main function you would use this function something like this
int main()
{
...
// look for person with id 5
int id = 5;
int index = sequential_search(firstArray, 12, id);
if (index == -1)
cout << "ID " << id << " not found\n";
else
cout << "ID " << id << " is " << firstArray[index].name << "\n";
}
Get the idea? Hopefully this gives you a start. You can do the rest, and ask again if you get into difficulties.

How to write Console terminal with C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am studying for an exam and need your help.
I must write my own console terminal in C++, which must work in this way:
Example:
:>plus 5 7 "hit ENTER"
:>12
:>minus 10 12 "hit ENTER"
:>-2
:>combine Hello World "hit ENTER"
:>HelloWorld
:>run netstat "hit ENTER"
:>runs netstat
:>help
:>plus int1 int2
minus int1 int2
combine string1 string2
run ?????
:>exit
program exits
For main block I think it would be something like this
int main(void) {
string x;
while (true) {
getline(cin, x);
detect_command(x);
}
return 0;
}
The functions would be something like this
void my_plus(int a, int b) {
cout << a + b;
}
void my_minus(int a, int b) {
cout << a - b;
}
void my_combine(string a, string b) {
?????????????;
}
void my_run(?????????) {
???????????;
}
And the finally detect_command
void detect_command(string a) {
const int arr_length = 10;
string commands[arr_length] = { "plus", "minus", "help", "exit" };
for (int i = 0; i < arr_length; i++) {
if (a.compare(0, commands[i].length(), commands[i]) == 0) {
?????????????????????;
}
}
}
????? - means I don`t know what to write.
Help to make this program work.
Thanks.
I'm going to use the minus operation as an example...
Make a structure like so:
struct cmd_struct {
const char *name;
void (*func) (void *data);
};
Since your function parameters aren't the same, you gotta make a structure for each, e.g.:
struct minus_op {
int rhs;
int lhs;
};
And use the cmd_struct as an array, like so:
static cmd_struct commands[] = {
{ "minus", &my_minus },
...
};
my_minus would then be:
void my_minus(void *data) {
struct minus_op *mop = data;
... do the computation and return ...
}
And loop through it to detect the command used:
for (int i = 0; i < sizeof(commands) / sizeof(commands[0]); ++i) {
if (strcmp(commands[i].name, a) == 0) {
... prepare the data ...
commands[i].func(data);
}
}
Side Note: In order to get the function parameters from command line, have a splitter, e.g. a white space. Use a vector for this and pass that vector to detect_command
Do also note: Get rid of the void param used in this example and use a char **argv and int argc like in main(). argv would be the arguments, and argc would be the number of arguments passed to the function. e.g. if you say to the program:
>> minus 5 1
Then argc should be 2 (the 5 and the 1) and argv[0] = "5" and argv[1] = "1".
Now that you know the idea behind it, implementing a more flexible version is left to you.
Call a respective function to handle each word. For example:
enum commands {
PLUS,
MINUS,
HELP,
EXIT
//....
};
int detect_command(string a) {
const int arr_length = 10;
string commands[arr_length] = { "plus", "minus", "help", "exit" };
for (int i = 0; i < arr_length; i++) {
if (a.compare(0, commands[i].length(), commands[i]) == 0)
return i;
}
return -1; //unknow word
}
Give the string to detect_command() the function return the respective integer to enum commands (that's our i value) or -1 if word is unknow. Then you can write a function like this to use and process the value determined by detect_command():
void run_command(int cmd)
{
switch(cmd) {
case PLUS: run_plus(); break;
case MINUS: run_minus(); break;
// and so on to all comamnds available
default: error("unknow command");
}
}
each function run_*() should continues the command parsing according to own rules, i.e, the "plus" command should be follow by one integer, one white-space and then another integer, right? run_plus() must validate it and then compute the result. e.g.:
//pseudo code
void run_plus()
{
//input here is one after "plus" word
//here we must validate our valid input: two digits split by a white-spaces
int x = parse_digit();
check(white-space);
int y = parse_digit();
int r = x + y;
display_result(r);
}
NOTE: I'm not a C++ programmer; I did detect_command() code modification to you get my idea. I even don't know if it will compile in C++ for the mismatch types.

Sorting using vectors [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm writing a program of a stock market where I read from a file and sort with symbols and percent gain/loss. I have completed sorting with symbols but having trouble establishing the percent gain loss. Basically i am instructed to use vectors. We are required to produce the list ordered by percent gain/loss and i need to sort the stock list by this component. However i'm not to physically sort the list by component percent gain/loss; instead provide a logical ordering with respect to this component.
so basically i added a data member, a vector to hold the indices of the stock list ordered by the component percent gain/loss. i called it array indexByGain. so when i print the list ordered by the percent gain/loss, i use the array indexByGain to print the list. my problem is an i need help on how to start if someone could show me an example or explain on how to go about this i can continue or correct me on my rough draft that will be helpful. below is a rough draft of my code. stockType has to do with the where data is stored from the file.
#include <iostream>
#include "stockType.h"
class stockListType
{
public:
void sortBySymbols();//sort out symbols and it comiples correctly.
void sortByGain();
void printByGain();
void insert(const stockType& item);
private:
vector<int> indexByGain;//declared a vector array indexByGain..
vector<stockType> list;
};
void stockListType::insert(const stockType& item)
{
list.push_back(item)//inserts the data from file to vector array.
}
//function prints out the gain
void stockListType::printByGain()
{
//my code to print out the gain..
}
//function to sort the gain and this is where i am stuck.
void stockListType::sortGain()
{
int i, j, min, maxindex;
for(i=0;i<list.size();i++)
{
min = i;
for(j=i+1;j<list.size();j++)
list[maxindex].getPercentage()<list[j].getPercentage();
maxindex = j;
indexGain.push_back(maxindex);
}
I know I am wrong but am i starting on a good base or totally of. please you could assist me or correct me. Thanks. oh sorry before i forget getPercentage() calculates and returns the percentage gain/loss.
Initialize the index and use std::sort:
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
struct Data {
int value;
int percent;
};
typedef std::vector<Data> DataVector;
typedef DataVector::size_type size_type;
typedef std::vector<size_type> IndexVector;
DataVector data { { 1, 1 }, { 2, -2 }, { 3, 3 }, { 4, -4 }, { 5, 5} };
IndexVector index;
index.resize(data.size());
for(size_type i = 0; i < data.size(); ++i) {
index[i] = i;
}
struct Less
{
const DataVector& data;
Less(const DataVector& data)
: data(data)
{}
bool operator () (size_type a, size_type b) {
return data[a].percent < data[b].percent;
}
};
std::sort(index.begin(), index.end(), Less(data));
for(size_type i = 0; i < index.size(); ++i) {
std::cout << data[index[i]].value << ": " << data[index[i]].percent << std::endl;
}
}
You may use C++11:
std::sort(index.begin(), index.end(),
[&](size_type a, size_type b) { return data[a].percent < data[b].percent; }
);
for(auto i: index)
std::cout << data[i].value << ": " << data[i].percent << std::endl;