why is a function-definition isn't allowed before "{"? - c++

We we're tasked to write a program that
Display the inputted strings,
Count the number of characters in the string(s),
Count the number of vowels in the string(s),
Count the number of consonants in the string(s),
Convert the string(s) to uppercase,
Convert the string(s) to lowercase,
Compare the two strings and Combine the two strings
Now, I'm facing a problem where everytime I try to run a program it gets an error that says function-definition is not allowed here before { token and error expected } at end of input.
Code below:
#include <cstring>
#include <string>
#include <iostream>
#include <stdio.h>
using namespace std;
void Display_Inputted_Strings()
{
string str1,str2;
cin >> str1;
cin >> str2;
cout << str1 << endl;
cout << str2 << endl;
return;
}
void The_Number_Of_Character()
{
char str1[10];
cout << "Input you're First String: ";
cin >> str1;
char str2[10];
cout << "Input you're Second String: ";
cin >> str2;
cout << "Lenght of string 1: " << strlen(str1) << endl;
cout << "Lenght of string 2: " << strlen(str2) << endl;
}
void The_Number_Of_Vowels()
{
bool isVowel(char ch)
{
{
ch = toupper(ch);
return (ch=='A' || ch=='E' || ch=='I' ||
ch=='O' || ch=='U');
}
}
}
int countVowels(int str)
{
int isVowel;
int count = 0;
for (int i=0; i<str.length(); i++)
if (isVowel(str[i]))
++count;
return count;
int str;
cout << "Enter a string: ";
cin >> str;
cout << "There are " << countVowels(str) << " Vowels in this string" << endl;
return 0;
}
void The_Number_Of_Consonants()
{
bool isConsonant(char ch)
{
ch = toupper(ch);
return !(ch == 'A' || ch == 'E' ||
ch == 'I' || ch == 'O' ||
ch == 'U') && ch >= 65 && ch <= 90;
}
int totalConsonants(string str)
{
int count = 0;
for (int i = 0; i < str.length(); i++)
if (isConsonant(str[i]))
++count;
return count;
string str;
cout << "Enter a string: ";
cin >> str;
cout << "There are a total of " << totalConsonants(str) << " Consonant";
}
}
void Convert_Strings_To_Uppercase()
{
void convert(string & s1)
{
for(int i = 0; i<s1.length(); i++)
{
s1[i] = toupper(s1[i]);
}
}
{
string s1;
cout << "Enter a string: " << endl;
getline(cin, s1);
convert(s1);
cout << s1 << endl;
return 0;
}
}
void Convert_Strings_To_Lowercase()
{
void convert(string & s1)
{
for(int i = 0; i<s1.length(); i++)
{
s1[i] = tolower(s1[i]);
}
}
{
string s1;
cout << "Enter a string: " << endl;
getline(cin, s1);
convert(s1);
cout << s1 << endl;
return 0;
}
}
void Compare_Two_Strings()
{
{
char str1[10] = "String";
char str2[10] = "Strings";
int result;
result=strcmp(str1,str2);
if(result==0)
cout << "String are equal" << endl;
else
cout << "String are not equal" << endl;
return 0;
}
}
void Combine_Two_Strings()
{
{
string s1, s2, result;
cout << "Enter string s1: ";
getline(cin,s1);
cout << "Enter string s2: ";
getline(cin,s2);
result = s1+s2;
cout << result << endl;
return 0;
}
}
void Input_String()
{
string str1;
cout << "Input a String: ";
cin >> str1;
cout << "The String You Inputted: " << str1;
}
void Exit_Program()
{
cout << "Thank You.\n";
}
int main()
{
int str1,str2;
{
cout << "Input Two Strings: ";
getline(cin, str1);
getline(cin, str2)
}
int selected
do
{
std::cout << "A.(0) Display Inputted Strings\n";
std::cout << "B.(1) Count the number of characters in the string(s)\n";
std::cout << "C.(2) Count the number of vowels in the string(s)\n";
std::cout << "D.(3) Count the number of consonants in the string(s)\n";
std::cout << "E.(4) Convert the string(s) to uppercase\n";
std::cout << "F.(5) Convert the string(s) to lowercase\n";
std::cout << "G.(6) Compare the two strings\n";
std::cout << "H.(7) Combine the two strings\n";
std::cout << "I.(8) Input another\n";
std::cout << "J.(9) Exit Program\n";
std::cin >> selected;
switch (selected)
{
case 0:
Display_Inputted_Strings();
break;
case 1:
The_Number_Of_Character();
break;
case 2:
The_Number_Of_Vowels();
break;
case 3:
The_Number_Of_Consonants();
break;
case 4:
Convert_Strings_To_Uppercase();
break;
case 5:
Convert_Strings_To_Lowercase();
break;
case 6:
Compare_Two_Strings();
break;
case 7:
Combine_Two_Strings();
break;
case 8:
Input_String();
break;
case 9:
Exit_Program();
break;
default:
std::cout << "You have entered an invalid option\n";
}
} while (selected != 9);
}
}

You probably come to the world of C++ from the world of another language like Python. It is not allowed to define a nested function within another function in C++. However you may define a lambda that may have the same semantics. For example:
void Convert_Strings_To_Lowercase()
{
auto convert = [](string & s1)
{
for(int i = 0; i<s1.length(); i++)
{
s1[i] = tolower(s1[i]);
}
};
{
string s1;
cout << "Enter a string: " << endl;
getline(cin, s1);
convert(s1);
cout << s1 << endl;
}
}
P.S. I've just converted your function into something compilable, without checking whether the code has any meaning. For example, I removed the return 0; statement as your function has the void return type.

Related

Hangman only gets first letter of secret word

I am trying to write a hangman program for an assignment. I've written code I thought would work, yet when testing it with the secret word, "IMPOSSIBLE", it only reads the "I" and nothing else. I tried changing all my strings to character lists but I don't think that was the issue. Does anyone have any advice on what I am doing incorrectly?
Thanks,
Keith.
Here is the code:
/* CSCI 261 Assignment 5: Hang Man Game
*
* Author: Keith Danielson
*
* A program that runs a simple hang man game
*/
// The include section adds extra definitions from the C++ standard library.
#include <iostream> // For cin, cout, etc.
#include <string>
// We will (most of the time) use the standard library namespace in our programs.
using namespace std;
//Defining the secret word as a constant
//const string SECRET_WORD = "IMPOSSIBLE";
int main() {
const char SECRET_WORD[10] = {'I','M','P','O','S','S','I','B','L','E'};
const int SECRET_WORD_LENGTH = 10;
//Defining the number of wrong guesses available, found letters, wrong guesses, and user choice.
int guesses = 7;
char foundLetters[SECRET_WORD_LENGTH];
char wrongGuesses[guesses];
char userChoice;
//Filling foundLetters with underslashes based on the length of the secret word.
for (int i = 0; i <= SECRET_WORD_LENGTH; i++) {
foundLetters[i] = '_';
}
cout << "Welcome to hangman!" << endl;
for (int i = 0; i <= 7; i++) {
if (guesses == 0){
break;
}
cout << "Take a guess: ";
for (int j = 0; j <= SECRET_WORD_LENGTH; j++) {
cout << foundLetters[j] << " ";
}
cout << "\n" << "Your guess: ";
cin >> userChoice;
//if the user input is lowercase it'll be made upper case.
if (islower(userChoice)) {
userChoice = toupper(userChoice);
}
for (int j = 0; j <= SECRET_WORD_LENGTH; j++) {
//if (userChoice == foundLetters[j]) {
// cout << "You already guessed" << userChoice << "." << endl;
// break;
//}
if (userChoice == SECRET_WORD[j]) {
cout << "There's a " << userChoice << "!" << endl;
foundLetters[j] = userChoice;
break;
}
else if (userChoice != SECRET_WORD[j]) {
guesses = guesses - 1;
cout << "Sorry. No " << userChoice << "'s." << endl;
wrongGuesses[i] = userChoice;
if (guesses == 0) {
cout << "You lose! Try again.";
break;
}
else {
cout << "You have " << guesses << " remaining." << endl;
break;
}
}
}
}
return 0; // signals the operating system that our program ended OK.
}
Try something more like this instead:
// The include section adds extra definitions from the C++ standard library.
#include <iostream> // For cin, cout, etc.
#include <string>
#include <limits>
// We will (most of the time) use the standard library namespace in our programs.
using namespace std;
//Defining the secret word as a constant
const char SECRET_WORD[10] = {'I','M','P','O','S','S','I','B','L','E'};
const int SECRET_WORD_LENGTH = 10;
//Defining the number of wrong guesses available
const int WRONG_GUESSES = 7;
bool hasLetter(const char *letters, int numLetters, char ch) {
for (int i = 0; i < numLetters; ++i) {
if (letters[i] == ch) {
return true;
}
}
return false;
}
int main() {
char foundLetters[SECRET_WORD_LENGTH];
int foundLetters = 0;
char wrongLetters[WRONG_GUESSES];
int wrongLettersLength = 0;
int wrongGuessesLeft = WRONG_GUESSES;
char userChoice;
int found;
//Filling foundLetters with underslashes based on the length of the secret word.
for (int j = 0; j < SECRET_WORD_LENGTH; ++j) {
foundLetters[j] = '_';
}
cout << "Welcome to hangman!" << endl;
while (true) {
cout << "Take a guess: ";
for (int j = 0; j < SECRET_WORD_LENGTH; ++j) {
cout << foundLetters[j] << " ";
}
cout << "\n";
cout << "Your guess: ";
cin >> userChoice;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//if the user input is lowercase it'll be made upper case.
userChoice = toupper(userChoice);
if (hasLetter(foundLetters, SECRET_WORD_LENGTH, userChoice) ||
hasLetter(wrongGuesses, wrongGuessesLength, userChoice))
{
cout << "You already guessed " << userChoice << "." << endl;
continue;
}
found = 0;
for (int j = 0; j < SECRET_WORD_LENGTH; ++j) {
if (SECRET_WORD[j] == userChoice) {
foundLetters[j] = userChoice;
++found;
}
}
if (found > 0) {
cout << "There's " << found << " " << userChoice << (found > 1 ? "'s" : "") << "!" << endl;
foundLettersLength += found;
if (foundLettersLength == SECRET_WORD_LENGTH) {
cout << "You win!";
break;
}
}
else {
cout << "Sorry. No " << userChoice << "'s." << endl;
wrongLetters[wrongLettersLength++] = userChoice;
if (--wrongGuessesLeft == 0) {
cout << "You lose! Try again.";
break;
}
cout << "You have " << wrongGuessesLeft << " guess" << (wrongGuessesLeft > 1 ? "es" : "") << " remaining." << endl;
}
}
return 0; // signals the operating system that our program ended OK.
}
Alternatively:
// The include section adds extra definitions from the C++ standard library.
#include <iostream> // For cin, cout, etc.
#include <string>
#include <limits>
#include <set>
// We will (most of the time) use the standard library namespace in our programs.
using namespace std;
//Defining the secret word as a constant
const string SECRET_WORD = "IMPOSSIBLE";
//Defining the number of wrong guesses available
const int WRONG_GUESSES = 7;
int main() {
//Filling foundLetters with underslashes based on the length of the secret word.
string foundLetters(SECRET_WORD.size(), '_');
set<char> guessedLetters;
int wrongGuessesLeft = WRONG_GUESSES;
char userChoice;
int found;
cout << "Welcome to hangman!" << endl;
while (true) {
cout << "Take a guess: ";
for (int j = 0; j < foundLetters.size(); ++j) {
cout << foundLetters[j] << " ";
}
cout << "\n";
cout << "Your guess: ";
cin >> userChoice;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
//if the user input is lowercase it'll be made upper case.
userChoice = toupper(userChoice);
if (!guessedLetters.insert(userChoice).second)
{
cout << "You already guessed " << userChoice << "." << endl;
continue;
}
string::size_type pos = SECRET_WORD.find(userChoice);
if (pos != string::npos) {
found = 0;
do {
foundLetters[pos] = userChoice;
++found;
pos = SECRET_WORD.find(userChoice, pos+1);
}
while (pos != string::npos);
cout << "There's " << found << " " << userChoice << (found > 1 ? "'s" : "") << "!" << endl;
if (foundLetters == SECRET_WORD) {
cout << "You win!";
break;
}
}
else {
cout << "Sorry. No " << userChoice << "'s." << endl;
if (--wrongGuessesLeft == 0) {
cout << "You lose! Try again.";
break;
}
cout << "You have " << wrongGuessesLeft << " guess" << (wrongGuessesLeft > 1 ? "es" : "") << " remaining." << endl;
}
}
return 0; // signals the operating system that our program ended OK.
}

How to add new row to a vector using struct in C++

Hello I am having issues with a final project. The objective is to have the user create a form that allows a user to view data, edit data, add data, and save their password data in an encoded format. The program starts with an input file made by the user. The delimiter is ';', and the first char is a "code", then the, site, username, password, and notes follow.
I am very new to vectors, and I am not allowed to use a 2d array, or map.
Thank you for your time.
#include <iomanip>
#include <cmath>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
const int MAX_SIZE = 30;
const int BUFFER_SIZE = 200;
struct dataRow {
string site, user, pass, notes;
string code;
};
string inFileName; //name of inputfile
string outFileName;
ifstream pathStream;
ofstream outFile;
char inputChar;
int extPosition(1), count = 0,lineNum;
void displayVector(vector<dataRow> inputData);
void viewLineData(vector<dataRow> inputData, int lineNum);
void addNewRow(vector<dataRow> inputData,int& lastRowNum, string site, string user, string pass, string notes);
void editLineData(vector<dataRow> inputData, int& lineNum, string site, string user, string pass, string notes);
void warning();
void cleanBuffer();
bool displayMenu();
int exit();
dataRow descripLine;
int main()
{
vector<dataRow> inputData;
string rowDescripin,userin,passin,notesin,sitein;
string codein,errorMsg;
int lastRow;
//add a .txt extension to the file if the user didn't provide an extension
if (inFileName.size() > 4)
// If there's a valid extension, it will be in the last 4 positions of the string; Adjust by 1 for 0 offset
extPosition = inFileName.size() - 4;
int ext = inFileName.find_last_of(".txt");
if (!(inFileName.find_last_of(".") == extPosition))
{
inFileName += ".txt";
}
cout << "\nPlease enter the filename of input file: ";
cin >> inFileName;
pathStream.open(inFileName.c_str());
if (pathStream.fail())
{
cerr << inFileName << " failed to open.\n";
system("pause");
exit(1);
}
else
{
cout << "startup success" << endl;
}
getline(pathStream, codein, ';');
descripLine.code = codein;
while (!pathStream.eof())
{
getline(pathStream, sitein, ';');
descripLine.site = sitein;
getline(pathStream, userin, ';');
descripLine.user = userin;
getline(pathStream, passin, ';');
descripLine.pass = passin;
getline(pathStream, notesin, ';');
descripLine.notes = notesin;
inputData.push_back(descripLine);
}
displayVector(inputData);
displayMenu();
while (cin){
cin >> inputChar;
inputChar = toupper(inputChar);
//Adjust calculations based on inputCHar
if (inputChar == 'D') // Display line descriptions
{
displayVector(inputData);
}
else if (inputChar == 'V') //View line data
{
cout << "Enter line number you wish to view: ";
cin >> lineNum;
viewLineData(inputData, lineNum);
}
/* else if (inputChar == 'E') //Edit line Data
{
cout << "Enter line number you wish to edit: ";
cin >> lineNum;
editLineData(inputData, lineNum);
}*/
else if (inputChar == 'A') //Add line data
{
warning();
lastRow = inputData.size();
cout << "Enter a line description: ";
cin >> rowDescripin;
cout << "Enter a line username: ";
cin >> userin;
cout << "Enter a line password: ";
cin>>passin;
cout << "Enter notes: ";
cin>>notesin;
addNewRow(inputData, lastRow, rowDescripin, userin, passin, notesin);
}
/*else if (inputChar == 'S') //Save and encode file
{
}*/
else if (inputChar == 'X') //exit program
{
exit();
}
}
system("pause");
}
bool displayMenu()
{
cout << endl << " AVAILABLE OPTIONS " << endl << endl <<
"D - DISPLAY LINE DESCRIPTIONS" << endl <<
"V - VIEW LINE DATA" << endl <<
"E - EDIT LINE DATA" << endl <<
"A - ADD LINE DATA" << endl <<
"S - SAVE AND ENCODE FILE" << endl <<
"X - EXIT PROGRAM" << endl;
return 0;
}
void viewLineData(vector<dataRow> inputData,int lineNum)
{
cout << inputData[lineNum].site << endl << inputData[lineNum].user<<endl<<inputData[lineNum].pass <<endl<<inputData[lineNum].notes;
}
void displayVector(vector<dataRow> inputData)
{
cout << fixed << setprecision(3);
for (unsigned int i = 0; i < inputData.size(); i++)
{
cout << left << setw(20) << inputData[i].site ;
}
}
void addNewRow(vector<dataRow> inputData, int& lastRowNum, string site, string user, string pass, string notes)
{
char ans;
cout << "You have entered:" << endl << site << endl << user << endl << pass << endl << notes<<endl;
cout << "Is this the data you wish to add (Y/N)? ";
cin >> ans;
ans = toupper(ans);
if (ans == 'Y')
{
dataRow tempRow = { site, user, pass, notes };
inputData.push_back(tempRow);
cout << inputData.size();
int num = inputData.size()-1;
for (unsigned int i = 0; i < inputData.size(); i++)
{
cout << inputData[i].site << endl << inputData[i].user << endl << inputData[i].pass << endl << inputData[i].notes;
}
}
else if (ans == 'N')
{
cout << "ok enter of no";
}
}
void warning()
{
cout<< "WARNING: You cannot use semi-colons in these fields. Any semi-colons entered will be removed." << endl;
return;
}
int exit()
{
pathStream.close();
system("pause");
return 0;
}
void cleanBuffer()
{
cin.clear();
cin.ignore(BUFFER_SIZE, '\n');
}

C++ : How to assign the same input to a string and an integer in 2 lines?

I'm a very beginner in C++ and I'm actually following the Google tutorial.
Trying to go a little further with the second example, here is my problematic : checking if the input is a number and, if not, being able to restate it in the error message.
Here is a way I used to solve that but the code length tells me that there is a shorter way :
#include <cstddef>
#include <iomanip>
#include <iostream>
#include <stdlib.h>
using namespace std;
bool IsInteger(string str) {
size_t non_num_position = str.find_first_not_of("0123456789-");
size_t sign_position = str.find_first_of("-", 1);
if (non_num_position == string::npos && sign_position == string::npos) {
return true;
}
return false;
}
void Guess() {
int input_number = 0;
string input_string;
do {
cout << "Try to guess the number between 0 and 100 (type -1 to quit) : ";
cin >> input_string;
if (!IsInteger(input_string)) {
int input_string_length = input_string.size();
cout << "Sorry but « " << input_string << " » is not a number." << endl;
cin.clear();
cin.ignore(input_string_length, '\n');
continue;
}
input_number = atoi(input_string.c_str());
if (input_number != -1) {
cout << "You chose " << input_number << endl;
}
} while (input_number != -1);
cout << "The End." << endl;
}
int main() {
Guess();
return 0;
}
Here is the shorter way I try to follow but cin seems to be "emptied" once assigned to input_number (because of the bitwise operator ?) :
void Guess() {
int input_number = 0;
string input_string;
do {
cout << "Try to guess the number between 0 and 100 (type -1 to quit) : ";
if (!(cin >> input_number)) {
getline(cin, input_string);
cout << "Sorry but " << input_string << " is not a number." << endl;
cin.clear();
cin.ignore(100, '\n');
continue;
}
if (input_number != -1) {
cout << "You chose " << input_number << endl;
}
} while (input_number != -1);
cout << "The End." << endl;
}
SOLUTION :
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
void Guess() {
int input_number = 0;
string input_string;
do {
cout << "Try to guess the number between 0 and 100 (type -1 to quit) : ";
cin >> input_string;
try {
input_number = stoi(input_string);
if (input_number != -1) {
cout << "You chose " << input_number << endl;
}
}
catch (const exception&) {
cout << "Sorry but " << input_string << " is not a number." << endl;
}
} while (input_number != -1);
cout << "The End." << endl;
}
int main() {
Guess();
return 0;
}
The problem with your first attempt is that IsInteger is unnecessarily complicated and long. Otherwise, you had the right idea. Your second attempt is much less correct.... once you read from cin, the data is gone. So, as in the first attempt, you need to store the data in a string.
Here's an example which is a little shorter and doesn't need IsInteger at all:
size_t p = 0;
int input_number = std::stoi(input_string, &p);
if (p < input_string.length())
{
cout << "Sorry but " << input_string << " is not a number." << endl;
conitnue;
}
stoi's second argument tells you where the conversion to integer stopped working. So if there was non-int data in the string (such as '123abc') then p will be somewhere before the end of the string. If p is at the end, then the whole string must have been a number.

C++ Hangman Code won't work correctly

my code compiles but it doesn't allow the user to guess the word correctly and when it displays the correct word, it is just a string of nonsense.
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
int instructions();
void manual();
void file(char*);
int letterFill(char, char*, char*);
void Unknown(char*, char*);
const int MAX_LENGTH = 10;
void main()
{
bool done = false;
char word[MAX_LENGTH];
char unknown[MAX_LENGTH];
char letter;
char name[MAX_LENGTH];
int wrong_guesses = 0;
int MAX_TRIES;
char ans;
while (!done)
{
switch (instructions())
{
case 1:
{
manual();
break;
}
case 2:
{
file(word);
break;
}
}
cout << "WHAT IS THE NUMBER OF GUESSES ALLOWED?: " << endl;
cin >> MAX_TRIES;
Unknown(word, unknown);
cout << endl << endl << "HANGMAN";
cout << endl << endl << "Each letter is represented by a star." << endl;
cout << "You have " << MAX_TRIES << " tries left.";
cout << "ENTER GUESS WHEN READY: ";
cin >> letter;
while (letter != 'N' && letter != 'n')
{
while (wrong_guesses < MAX_TRIES)
{
cout << unknown << endl;
cout << "Guess a letter: " << flush;
cin >> letter;
if (letterFill(letter, word, unknown) == 0)
{
cout << endl << "You got it wrong! You lose a guess" << endl;
wrong_guesses++;
}
else
{
cout << endl << "Pfft, you got lucky" << endl;
}
cout << "Guesses Left: " << MAX_TRIES - wrong_guesses << endl;
if (strcmp(word, unknown) == 0)
{
cout << word << endl;
cout << "You got it!" << endl;
exit(0);
}
cout << "You've been hanged." << endl;
cout << "The word was : " << word << endl;
}
}
cout << "Try again? (y/n): " << flush;
cin >> ans;
if (ans == 'y' || ans == 'Y')
done = true;
else
done = false;
}
system("pause");
}
int instructions()
{
int select = 0;
cout << endl << "HANGMAN" << endl << endl;
cout << " PROGRAM MENU" << endl;
cout << " Select option 1 or 2" << endl << endl;
cout << " 1. INPUT WORD MANUALLY" << endl;
cout << " 2. PLAY AGAINST THE COMPUTER" << endl;
cout << " 3. EXIT PROGRAM BY INPUTING: N or n" << endl << endl;
cin >> select;
return select;
}
void manual()
{
string word;
cout << endl << "INPUT WORD: " << endl;
cin >> word;
return;
}
void file(char *roc)
{
ifstream fin("word.txt");
int x;
int count = 1;
int word;
int i = 0;
srand(time(0));
word = rand() % 20;
while (count < word)
{
fin >> x;
if (x == 0)
{
count++;
}
}
do
{
fin >> x;
roc[i++] = char(x);
} while (x);
return;
}
int letterFill(char guess, char *secretword, char *guessword)
{
int i;
int matches = 0;
for (i = 0; i<MAX_LENGTH; i++)
{
if (secretword[i] == 0)
{
break;
}
if (guess == guessword[i])
{
return 0;
}
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
void Unknown(char *word, char *unknown)
{
int i;
int length = strlen(word);
for (i = 0; i<length; i++)
{
unknown[i] = '*';
}
unknown[i] = 0;
}
Again
my code compiles but it doesn't allow the user to guess the word correctly and when it displays the correct word, it is just a string of nonsense.

Vectors with cout operator issue in C++

In my program, I am encountering an error with trying to print the end() of a vector. Here is the code:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <time.h>
#include "inFrench.h"
using namespace std;
class student
{
int m_studentNumber;
public:
string nameFirst;
string nameLast;
string nameFull;
int getStudentNumber() { return m_studentNumber; }
void setStudentNumber(int studentNumber) { m_studentNumber = studentNumber; }
};
class group
{
public:
vector<student> groupMembers;
};
ostream& operator<<(ostream& os, const student& s)
{
return os << s.nameFirst << ' ' << s.nameLast;
}
student typeName()
{
student bar;
cout << "Type in a student's first name: ";
cin >> bar.nameFirst;
cout << "Type in that student's last name: ";
cin >> bar.nameLast;
bar.nameFull = bar.nameFirst + " " + bar.nameLast;
return bar;
}
void displayStudents(student listOfStudents[50], int studentHeadCount)
{
for (int i = 0; i < studentHeadCount; i++)
{
cout << listOfStudents[i].nameFull << endl;
cout << listOfStudents[i].getStudentNumber() << endl;
cout << "\n";
}
}
void generateGroups(int numberOfGroups, int maxStudents, int studentsPerGroup, int remainder, group foo, student theStudents[], int studentsBeenAssigned)
{
int k;
numberOfGroups = maxStudents / studentsPerGroup;
cout << numberOfGroups << endl;
srand(time(NULL));
while (studentsBeenAssigned << maxStudents)
{
for (int j = 0; j < maxStudents; j++)
{
k = rand() % maxStudents;
foo.groupMembers.push_back(theStudents[k]);
cout << foo.groupMembers.end() << endl;
studentsBeenAssigned++;
}
}
if (remainder < studentsPerGroup && remainder > 0) // Still coding this section
{
foo.groupMembers.push_back(theStudents[k]);
}
}
void languageChoices()
{
cout << "Select your language from the following:\n";
cout << "a) English\n";
cout << "b) French\n";
cout << "\n";
}
void options()
{
cout << "Select what you want to do:\n";
cout << "1) Exit application\n";
cout << "2) Enter a Student\n";
cout << "3) Display Students\n";
cout << "4) Display Groups\n";
cout << "5) Output groups as text file\n";
cout << "\n";
}
int main()
{
char selectedLanguage;
languageChoices();
cin >> selectedLanguage;
switch (selectedLanguage)
{
case 'a':
{
group finishedListOfStudents;
student allStudents[50]; // Having 50 students alone is ridiculous!
bool endProg = 0;
int maxStudents;
int studentsPerGroup;
int optionSelect;
int studentHeadCount = 0;
int remainder = 0;
int numberOfGroups;
int studentsBeenAssigned;
cout << "GroupPicker 1.0\n";
cout << "Note: This version of the program is intended for purposes of education only, "
<< "specifically for teacher use in a classroom.\n\n";
cout << "How many students are in the class?\n" << "(Note: You cannot have more than 50 in this program)\n";
cin >> maxStudents;
if (maxStudents > 50)
{
cerr << "Too many students!\n" << "Exiting program...\n";
system("PAUSE");
exit(1);
}
if (maxStudents >= 35 && maxStudents <= 50)
{
cout << maxStudents << " students? You are a pro!\n";
}
cout << "How many students per group?\n";
cin >> studentsPerGroup;
if (studentsPerGroup >= maxStudents || studentsPerGroup <= 1)
{
cerr << "You're kidding, right?\n" << "Exiting program...\n";
system("PAUSE");
exit(1);
}
while (endProg == 0) {
options();
cin >> optionSelect;
switch (optionSelect) {
case 1:
endProg = 1;
break;
case 2:
{
if (studentHeadCount == maxStudents)
{
cerr << "You can't enter more than " << maxStudents << " students\n";
}
else
{
allStudents[studentHeadCount] = typeName();
allStudents[studentHeadCount].setStudentNumber(studentHeadCount);
cout << "Student (" << allStudents[studentHeadCount].nameFull << ") entered.\n";
cout << "\n";
studentHeadCount++;
}
break;
}
case 3:
cout << "Current list of students:\n\n";
displayStudents(allStudents, studentHeadCount);
break;
case 4:
{
if (studentHeadCount < studentsPerGroup || studentHeadCount < maxStudents)
{
cerr << "Invalid group parameters.\n" << "Returning to main menu...\n\n";
break;
}
else
{
cout << "Here are the groups:\n";
generateGroups(numberOfGroups, maxStudents, studentsPerGroup, remainder, finishedListOfStudents, allStudents, studentsBeenAssigned);
}
break;
}
case 5:
{
cout << "Saving groups to file...\n";
ofstream studentGroups;
studentGroups.open("studentGroups.txt");
break;
}
}
}
break;
}
case 'b':
{
mainInFrench();
}
}
}
I get the following results:
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::_Vector_iterator<_Myvec>' (or there is no acceptable conversion) [Line 66]
IntelliSense: no operator "<<" matches these operands. operand types are: std::ostream << std::_Vector_iterator<std::_Vector_val<std::_Simple_types<student>>> [Line 66]
I have considered overloading the ostream operator<< operator again, but is there another option?
std::vector::end() returns an iterator to the end of the vector , not the actual last element.
You could print the last item like this instead:
cout << foo.groupMembers.at(foo.groupMembers.size() - 1);
Turns out, I never needed the vector in the first place. I just had to use the arrays. I have answered my own question.