Sorting alphabetically - c++

Here is my code...What would be the best way to sort names alphabetically?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int StudentNum;
cout << "How many student are in the class?\n";
cin >> StudentNum;
string sname[25];
if (StudentNum < 1 || StudentNum > 25)
{
cout << "Please enter a number between 1-25 and try again\n";
return 0;
}
for (int i = 1; i <= StudentNum; i++)
{
cout << "Please enter the name of student #" << i << endl;
cin >> sname[i];
}
for (int output = 0; output <=StudentNum; output++)
{
cout << sname[output] << endl;
}
system ("pause");
return 0;
}

The standard way is to use std::sort:
#include <algorithm>
// ...
std::sort(sname, sname + StudentNum);
std::sort uses operator< by default, which actually does an alphabetical comparison for strings.
EDIT: Indeed, it should be StudentNum instead of 25.

Related

How to connect sections of an array or organize an array the same as another?

I am not sure how to connect a part of an array or if it is even possible.
My code is as follows:
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
string name;
string date[3];
double height[3];
double enter;
cout << "Enter name of a pole vaulter: ";
cin >> name;
cout << "Enter date of first vault: ";
cin >> date[0];
cout << "Enter height of first vault: ";
cin >> enter;
if (enter >= 2.0)
{
if (enter <= 5.0)
{
height[0] = enter;
}
else
{
cout << "Incorrect Value";
abort();
}
}
else
{
cout << "Incorrect Value";
abort();
}
cout << "Enter date of second vault: ";
cin >> date[1];
cout << "Enter height of second vault: ";
cin >> enter;
if (enter >= 2.0)
{
if (enter <= 5.0)
{
height[1] = enter;
}
else
{
cout << "Incorrect Value";
abort();
}
}
else
{
cout << "Incorrect Value";
abort();
}
cout << "Enter date of third vault: ";
cin >> date[2];
cout << "Enter height of third vault: ";
cin >> enter;
if (enter >= 2.0)
{
if (enter <= 5.0)
{
height[2] = enter;
}
else
{
cout << "Incorrect Value";
abort();
}
}
else
{
cout << "Incorrect Value";
abort();
}
int len = sizeof(height) / sizeof(height[0]);
sort(height, height + len, greater<int>());
cout << "Stats for " << name << ":" << endl;
for (int i = 0; i < len; i++) {
cout << height[i] << " ";
}
cout << height[0];
}
I am trying to enter dates and a double value, and then organize the double values in descending order and keep the dates with the corresponding value. I am not sure if this is possible, any alternative way of completing this would be helpful.
Thank you
Group of data, data sorting, multiple data points that should be aligned/connected to their respective other data points. I think the best solution here would be the use of a struct or class with vectors:
Let's say you want a variable that contains both your date and number. We can construct a class or structure for that:
#include <iostream>
using namespace std;
struct str1
{
string date;
double number;
};
class cls1
{
public:
string date;
double number;
};
int main()
{
str1 ob1;
cls1 ob2;
ob1.date = "somedate";
ob1.number = 12345;
cin >> ob1.date;
cout << ob1.date << " " << ob1.number << endl;
ob2.date = "somedate2";
ob2.number = 54321;
cin >> ob2.number;
cout << ob2.date << " " << ob2.number << endl;
return 0;
}
Having a class or struct enables you to use objects (variables made from those structs or classes). Every object created has their own place in memory for storing both date and number. You can use, find, search any of these variables and have access to both values this way.
Grouping them up so there's a list of them can be done in vectors.
Vectors are like better arrays. They not only have a dynamical size (meaning its size can change and doesnt stay static like in arrays), but they also have quite a bit ready made functions for you to use:
bool sortingFunction(int &a, int &b)
{
if (a > b) return true;
else return false;
}
int main2()
{
vector<int> numbers;
//to add
numbers.emplace_back(5); //5 is the number to add
//to remove
numbers.erase(numbers.begin() + 2); //2 is the index of the variable to delete
//to sort
sort(numbers.begin(), numbers.end(), sortingFunction);
return 0;
}
Vectors need the #include <vector> header.
Sort is a function that sorts. Needs #include <algorithm> header.
Sort function is neat because you can define the logic behind how you want to sort the vector or array with a seperate function that returns either true or false.
For your example you could do something like this in the end:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct myType
{
string date;
double number;
};
bool sortByDate(myType &a, myType &b)
{
if (a.date > b.date) return true;
else return false;
}
bool sortByNumber(myType &a, myType &b)
{
if (a.number > b.number) return true;
else return false;
}
int main()
{
vector<myType> variables;
int num;
cout << "how many do you want to add" << endl;
cin >> num;
for(int i = 0; i < num; i++)
{
myType tmp;
cout << "Enter date of var" << i+1 << ": ";
cin >> tmp.date;
cout << "Enter number of var" << i+1 << ": ";
cin >> tmp.number;
variables.emplace_back(tmp);
}
//after that you can use the vector as you want...
//sort
sort(variables.begin(), variables.end(), sortByDate);
sort(variables.begin(), variables.end(), sortByNumber);
//delete
variables.erase(variables.begin()+5);
//or clear the entire thing
variables.clear();
//Either way each item in the vector consists of both number and date thus even
//if you sort the vector the values are still connected at the same position
return 0;
}

Cannot get my getchar() function to work how I want it to work, output is10 not 2 c++

I cannot figure out why my getchar() function is not working the way I want it to work. I am getting 10 not 2. Please take a look.
Main():
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int var, newvar;
cout << "enter a number:" << endl;
cin >> var;
newvar = getchar();
cout << newvar;
return 0;
}
Here is my output:
enter a number:
220
10
Ultimately though I need to be able to distinguish between a '+' '-' or letter or number.
This is maybe not the cleanest way to do it but you can get every char one by one :
#include <iostream>
using namespace std;
int main()
{
int var;
cout << "enter a number:" << endl;
cin >> var;
std::string str = to_string(var);
for(int i=0; i < str.length();++i)
cout << str.c_str()[i] << endl;
return 0;
}
If you enter for example: "250e5" it will get only 250 and skip the last 5.
Edit:
This is just a simple parser and does not do any logic.
If you want to make a calculator I would recommend you to look at what Stroustrup did in his book the c++ programming language.
int main()
{
string str;
cout << "enter a number:" << endl;
cin >> str;
for(int i=0; i < str.length();++i) {
char c = str.c_str()[i];
if(c >= '0' && c <= '9') {
int number = c - '0';
cout << number << endl;
}
else if(c == '+') {
// do what you want with +
cout << "got a +" << endl;
} else if(c == '-')
{
// do what you want with -
cout << "got a -" << endl;
}
}
return 0;
}

c++ pushing array elements to the right

I am newbie into programming and have this c++ school quizzes.
I wanted to push entered arrays elements to the right.
here is my existing code
Blockquote
// automatac++.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <list>
#include <iterator>
#include <conio.h>
#include <cstring>
//using namespace std;
using std::cout;
using std::cin;
using std::endl;
void menu_sel();
void push_element();
//void rem_element();
int in;
char array[100];
int p_elements;
int main()
{
menu_sel();
return 0;
}
void push_element() {
int p_elements;
for (int e = 0; e < 10; e++) {
}
cout << "Enter number of elements:";
cin >> p_elements;
cout << "Enter only " << p_elements << " elements"<<endl;
for (int e = 0; e < p_elements; e++ ) {
cin >> array[e];
}
cout << "Pushed elements are :";
for (int e = 0; e < p_elements; ++e) {
cout << array[e]<<" ";
}
//getch();
menu_sel();
}
/*
void rem_element() {
char remove;
int arr_position;
cout << "You have selected Pop.\nRemove elements from arrays \n";
cout << "Enter data to remove";
cin >>remove;
for (int ie -) {
}
system("pause");
}
*/
void menu_sel() {
int input;
cout << "\n****Menu Selection Here****";
cout << "\n1. Push \n2. Pop \n3. Exit \n";
cout << "select options here :";
cin >> input;
switch (input) {
case 1:
cout << "You have selected Push Stack\n";
push_element();
break;
case 2:
//cout << "You have selected Pop Stack\n";
//rem_element();
break;
default:
cout << "You have selected Invalid Options";
break;
system("cls");
return;
}
}
and here is the output
the output shows pushing elements to the left
the output was 3 e r 4
I wanted to shows output like this "4 r e 3"
thanks and regards,
You can always read your array backwards for output if you want to show it that way.
for (int e = p_elements-1; e >= 0; --e) {
cout << array[e]<<" ";
}

Validate case pattern (isupper/islower) on user input string

I need to write a program that checks if the user-provided first and last names are correctly typed. The program needs to validate that only the first letter of each name part is uppercase.
I managed to write code that checks the first character of the input. So I have a problem when for example "JOHN" is entered.
A correct input would be for example "John Smith".
Here's the code:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
std::string str;
cout << "Type First Name: ";
cin >> str;
if(isupper(str[0]))
{
cout << "Correct!" <<endl;
}
else
{
cout << "Incorrect!" <<endl;
}
system("pause");
return 0;
}
The simplest thing you can do is to use a for/while loop. A loop will basically repeat the same instruction for a number of n steps or until a certain condition is matched.
The solution provided is pretty dummy, if you want to read the first name and last name at the same time you will have to spit the string via " " delimiter. You can achieve this result using strtok() in C/C++ or with the help of find in C++. You can see some examples of how to split here.
You can easily modify your code to look like this:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
std::string str;
std::vector<std::string> data = { "First", "Last" };
int j;
for (int i = 0; i < 2; i++) {
cout << "Type " << data[i] << " Name: ";
cin >> str;
if (isupper(str[0])) {
for (j = 1; j < str.size(); j++) {
if (!islower(str[j]))
{
cout << "InCorrect!" << endl;
break; // Exit the loow
}
}
if(j==str.size())
cout << "Correct!" << endl;
}
else {
cout << "InCorrect!" << endl;
}
}
system("pause");
return 0;
}

char uninitialized, isnumber method unidentified,

I'm having errors in my code below,
This is my code:
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> numbers(0);
cout << "please enter you numbers :::\n''entering any characters but numbers is the end of entry''";
char ch;
int i = 0;
while (Isnumber(ch)){ //here is the error
do{
ch = getchar();
int newnumber = 0;
cout << "element(" << i << ") = ";
cin >> newnumber;
numbers.push_back(newnumber);
} while (ch>0 || ch < 9);
}
getchar();
}
two errors,
it says that identifier is unknown,
and
it says variable char is uninitialazed local variable,
change this while (Isnumber(ch)){ into do-while loop.
do{
.....
}while (Isnumber(ch))
The error is because ch is declared and it is used before initialized.
Also include #include <stdio.h>; for getchar();
Better do it in one loop:
do {
ch = getchar();
int newnumber = 0;
cout << "element(" << i << ") = ";
cin >> newnumber;
numbers.push_back(newnumber);
} while (Isnumber(ch)); // should probably be isdigit(ch)
And before asking similar questions read this first (or buy a book).
Well I solved it using cin functions as below,
#include "stdafx.h"
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<int> numbers(0);
cout << "please enter you numbers :::\n''entering any characters but numbers is the end of entry''\n";
//char ch;
int counter = 0;
do{
int newnumber = 0;
cout << "element(" << counter << ") = ";
counter++;
cin >> newnumber;
numbers.push_back(newnumber);
if (cin.fail()){
cout << "entered numbers are:\n";
for (vector<int>::iterator i = numbers.begin(); i != numbers.end(); i++)
{
cout << *i;
if (i != numbers.end()-1)cout << " - ";
}
}
} while (cin.good());
getchar();
}
I removed one while loop.
and used cin.fail and cin.good to avoid using IsNumber. And it worked.