Reading a file from user input c++ - c++

I have been trying to get this to work for an hour now and I know it can't be that difficult a fix. Every time I enter the file.txt name it comes up as invalid file. I tried moving the files to the same directory as the .cpp file and everything but I just cant get it to read. Help would be appreciated.
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<assert.h>
using namespace std;
const int SIZE = 20;
void readIntFile(ifstream& x, int intArray[], int size, int &length);
void printValues(int intArray[], int& length);
char getSentinel();
int main()
{
ifstream inputStream;
const int size = SIZE;
string fileName;
int length = 0;
bool isEmpty = false;
int intArray[size];
char sentinel = 'y';
while (sentinel == 'y' || sentinel == 'Y')
{
cout << "Please enter the name of the file: ";
cin >> fileName;
inputStream.open(fileName);
if (inputStream.bad() || inputStream.fail())
{
cout << "Error, <" << fileName << "> is Invalid File Name.";
}
if (fileName.empty())
{
isEmpty = true;
}
if (isEmpty == true)
{
cout << "Error <" << fileName << "> has no data.";
}
if (inputStream.good() && isEmpty == false)
{
readIntFile(inputStream, intArray, size, length);
printValues(intArray, length);
inputStream.close();
}
sentinel = getSentinel();
}
return 0;
}
void readIntFile(ifstream& x, int intArray[], int size, int& length)
{
int count = 0;
int arrayLocation = -1;
int fileInputValue = 0;
x >> fileInputValue;
while (!x.eof())
{
count ++;
if (count > SIZE)
{
cout << "The file has more than <" << SIZE << "> values." << endl;
break;
}
else
{
arrayLocation ++;
intArray[count] = fileInputValue;
x >> fileInputValue;
}
}
}
void printValues(int intArray[], int& length)
{
assert(length > 0);
cout << "<" << length << "> values processed from the file. The values are: ";
for (int i=0; i <= length; i++)
{
cout << intArray[i] << ", ";
}
}
char getSentinel()
{
char userInput = 'n';
bool inputCheck = false;
cout << "Do you wish to process another file (y/n)?" << endl;
cin >> userInput;
do
{
if (userInput == 'y' || userInput == 'Y' || userInput == 'n' || userInput == 'N')
{
inputCheck = true;
}
else
{
cout << "Invalid response: <" << userInput << ">" << endl;
cout << "Do you wish to process another file (y/n)?" << endl;
cin >> userInput;
}
} while (!inputCheck);
return userInput;
}

Your basic problem is in function
void readIntFile(ifstream& x, int intArray[], int size, int& length)
You do not set the output variable length. And you use the wrong index value for your array. Please check.
Additionally there are many other problems in your code.
I will now paste your code, amended with my comments comments, where problems are or where things should be improved.
Please see:
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<assert.h>
using namespace std; // Should never be used. Always use fully qualified names
const int SIZE = 20; // Please use constexpr
// Do not use C-Style function prototypes. Put main at the bottom
// Do not use C-Style Arrays
// In C++ (C-Style-)Arrays are different. You actually do not pass an array to your function
// but a decyed pointer. You can pass an array by pointer or by reference, but this has a different syntax
void readIntFile(ifstream& x, int intArray[], int size, int &length);
void printValues(int intArray[], int& length);
char getSentinel();
int main()
{
// All variables shall be initialized at the point of defintion
ifstream inputStream; // You should define variables just before you need then
const int size = SIZE; // This is code duplication. And constexpr should be used
string fileName;
int length = 0;
bool isEmpty = false;
int intArray[size]; // C-Style Arrays should not be used. Use std::array or best, std::vector
char sentinel = 'y'; // You could use universal initializer syntax with braced initializer
while (sentinel == 'y' || sentinel == 'Y')
{
cout << "Please enter the name of the file: ";
cin >> fileName;
inputStream.open(fileName); // The constructor can open the file for you
if (inputStream.bad() || inputStream.fail()) // This is too complicated
{
cout << "Error, <" << fileName << "> is Invalid File Name.";
}
if (fileName.empty()) // Check is too late and not necessary
{
isEmpty = true;
}
if (isEmpty == true)
{
cout << "Error <" << fileName << "> has no data.";
}
if (inputStream.good() && isEmpty == false)
{
readIntFile(inputStream, intArray, size, length);
printValues(intArray, length);
inputStream.close(); // Destructor will clsoe the file for you
}
sentinel = getSentinel();
}
return 0;
}
// Not optimal function prototype
void readIntFile(ifstream& x, int intArray[], int size, int& length)
{
// the whole design / logic is very strange
int count = 0;
int arrayLocation = -1; // More then strange. Shows that this is a bad design
int fileInputValue = 0;
x >> fileInputValue;
while (!x.eof()) // Bad or even wrong design
{
count ++; // Wrong. See below. array will be filled with starting with index one
if (count > SIZE)
{
cout << "The file has more than <" << SIZE << "> values." << endl;
break;
}
else
{
arrayLocation ++; // This variable is not used
intArray[count] = fileInputValue;
x >> fileInputValue;
}
}
// Nobody will set the length variable
}
void printValues(int intArray[], int& length)
{
assert(length > 0); // Basically OK, but no necessary here. Cannoz happen
cout << "<" << length << "> values processed from the file. The values are: ";
for (int i=0; i <= length; i++)
{
cout << intArray[i] << ", ";
}
// There is now newline character used anywhere
}
// Very complicated
char getSentinel()
{
char userInput = 'n';
bool inputCheck = false;
cout << "Do you wish to process another file (y/n)?" << endl;
cin >> userInput;
do
{
if (userInput == 'y' || userInput == 'Y' || userInput == 'n' || userInput == 'N')
{
inputCheck = true;
}
else
{
cout << "Invalid response: <" << userInput << ">" << endl;
cout << "Do you wish to process another file (y/n)?" << endl;
cin >> userInput;
}
} while (!inputCheck);
return userInput;
}
Next, I will make your code working, by fixing the biggest problems. I will still follow your programming style.
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<assert.h>
constexpr int MaxArraySize = 20;
using IntArray = int[MaxArraySize];
void readIntFile(std::ifstream& x, int intArray[], int& length)
{
length = 0;
int value{};
while (x >> value)
{
if (length >= MaxArraySize)
{
std::cout << "The file has more than <" << MaxArraySize << "> values.\n";
break;
}
else
{
intArray[length++] = value;
}
}
}
void printValues(int intArray[], int& length)
{
std::cout << "\n<" << length << "> values processed from the file. The values are: ";
for (int i=0; i < length; i++)
{
std::cout << intArray[i] << ", ";
}
std::cout << "\n\n";
}
bool getSentinel()
{
char userInput{'n'};
bool valid = false;
while (not valid)
{
std::cout << "\n\nDo you wish to process another file (y/n)?\n";
std::cin >> userInput;
if (userInput != 'y' && userInput != 'Y' && userInput != 'n' && userInput != 'N')
{
std::cout << "Invalid response: <" << userInput << ">\n\n";
}
else {
valid = true;
}
}
return ( userInput=='y' || userInput=='Y');
}
int main()
{
int intArray[MaxArraySize];
bool sentinel = true;
while (sentinel)
{
std::cout << "Please enter the name of the file: ";
std::string fileName{};
std::cin >> fileName;
if (fileName.empty())
{
std::cout << "Error <" << fileName << "> has no data.\n\n";
}
else {
std::ifstream inputStream(fileName);
if (!inputStream)
{
std::cout << "Error, <" << fileName << "> is Invalid File Name.\n\n";
}
else
{
int length = 0;
readIntFile(inputStream, intArray, length);
printValues(intArray, length);
}
}
sentinel = getSentinel();
}
return 0;
}
and, in the end, because we are in a C++ site here, I will show (one of many possible) a more advanced C++ solution.
This is just for information and to grab some ideas for the future
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<vector>
#include<algorithm>
#include<iterator>
#include<initializer_list>
// Some aliases for easier reading and saving typing work
using DataType = int;
using Vector = std::vector<DataType>;
// Define an "in" operator
struct in {
in(const std::initializer_list<char>& il) : ref(il) {}
const std::initializer_list<char>& ref;
};
bool operator,(const char& lhs, const in& rhs) {
return std::find(rhs.ref.begin(), rhs.ref.end(), lhs) != rhs.ref.end();
}
int main() {
// As long as the user wants to read files
for (bool userWantsToContinue{true}; userWantsToContinue;) {
std::cout << "\nPlease enter a valid filename: ";
if (std::string filename{}; std::cin >> filename) {
// Open the file for reading and check, it it is open
if (std::ifstream inputStream{filename}; inputStream) {
// Read all data from the file
Vector data(std::istream_iterator<DataType>(inputStream), {});
// Now show result to user
std::cout << "\nRead values are:\n";
std::copy(data.begin(), data.end(), std::ostream_iterator<DataType>(std::cout, " "));
}
else std::cerr << "\nError: Could not open file '" << filename << "' for reading\n\n";
}
else std::cerr << "\nError: Problem with filename input\n\n";
// Ask, if the user wants to continue
bool validInput{false};
while (not validInput) {
std::cout << "\n\nDo you want to read more files? Please enter 'y' or 'n' ";
if (char selection{}; (std::cin >> selection) && (selection, in{'y','Y','n','N',}) ) {
validInput = true;
userWantsToContinue = (selection, in{'y','Y'});
}
else {
std::cout << "\n\nInvalid input, please retry\n\n";
}
}
}
return 0;
}

Try using an full absolute filename, not a relative one.
And replace cin >> fileName; with std::getline(std::cin, fileName); Otherwise, it will easily break. The getline version is much more robust.
If this was not enough, read the answer of: How do I get the directory that a program is running from? and do the checks suited for your system to find out your "working directory". This is the place where you input file must be, if you don't use absolute paths.

Related

Dealing with file io in c++

I have a program that takes input for names and outputs the last names in a string. The task I have now is to include FileIO in it. Specifically, "get user input for the filename, and then read the names from the file and form the last name string."
When I run the program, the console will show the name string from the text file. But only initially. As you keep entering names, that string disappears. Also, my user input for file name seems to be doing nothing, because I can enter anything and it still show the string of last names from the text file.
Here is what I have so far. Included all of it, just to make sure.
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
using namespace std;
// function declerations
int Menu();
void getName(vector<string> &names, int &count);
void displayName(vector<string> &names, int count);
string getLastNames(vector<string> &names, int count);
int main()
{
vector<string> names;
int count = 0;
int choice = Menu();
ifstream File;
string line;
cout << "Enter file name: ";
getline(cin,line);
File.open("File.txt");
while(File.good()){
getline(File,line);
cout << line << endl;
}
File.close();
while (choice != 0)
{
// switch statement to call functions based on users input
switch (choice)
{
case 1: {
getName(names, count);
} break;
case 2: { displayName(names, count); } break;
case 3: {
cout << getLastNames(names, count) << endl;
} break;
case 0: {
return 0;
} break;
}
choice = Menu();
}
return 0;
}
// function definition for vector of strings
void getName(vector<string> &names, int &count)
{
string name;
// get input for name
cout << "Enter name: ";
getline(cin, name);
// find position of space in string
int pos = name.find(' ');
// reverse order of name
if(pos != -1) {
string first = name.substr(0, pos);
string last = name.substr(pos+1);
name = last + "," + first;
}
// add name to end of vector
names.push_back(name);
count++;
}
// give user option of what to do
int Menu() {
int choice;
cout << "1. Add a name" << endl;
cout << "2. Display names " << endl;
cout << "3. Show all Last Names" << endl;
cout << "0. Quit" << endl;
cout << "Enter a option: ";
cin >> choice;
// if outside of above choices, print 'choice not on list'
while (choice < 0 || choice > 3)
{
cout << "Choice not on list: ";
cin >> choice;
}
cin.ignore();
return choice;
}
// defining function that gets last names
string getLastNames(vector<string> &names, int count) {
stringstream ss;
for (int i = 0; i<count; i++)
{
int pos = names[i].find(',');
if (pos != -1) {
ss << "\"" << names[i].substr(0, pos) << "\", ";
} else {
ss << "\"" << names[i] << "\", ";
}
}
return ss.str();
}
// display the names
void displayName(vector<string> &names, int count)
{
if (count == 0)
{
cout << "No names to display" << endl;
return;
}
for (int i = 0; i<count; i++)
{
cout << names[i] << endl;
}
}

How to find rows that contains the exact content that i need in c++

So i have this mini project for school, it's login and register system.
It is almost complete, except for comparing the data. My idea is, when people register, their data will be stored in either txt or csv file. Their name will be in odd row and their password will be stored in even rows.
So, when people login, as they enter their name, the program will find the name's row, and then go down a row to compare the real password with the login password. So how do i find the name's row? Thanks a lot.
This is my code so far, i'm new to this coding, so it might looks stupid
#include<iostream>
#include<conio.h>
#include <fstream>
#include"sosanh.h"
include"docdulieu.h"
using namespace std;
struct nguoidung
{
char tentaikhoan[20], matkhau[16], taikhoankhac[20];
};
nguoidung dulieu;
string line;
int main()
{
ifstream input_file(filename);
if (!input_file.is_open())
{
cout << "Could not open the file - '"
<< filename << "'" << endl;
return EXIT_FAILURE;
}
int luachon;
char yesorno;
cout << "1, Dang nhap" << endl << "2, Dang ky" << endl;
luachon = _getch();
switch (luachon)
{
case 1:
cout << "Nhap ten tai khoan: " << endl;
for (int a, a < 20, a++)
{
dulieu.tentaikhoan[a] = _getch();
while (getline(input_file, line))
{
strcpy(dulieu.taikhoankhac, line.c_str());
array_equal(const char* dulieu.tentaikhoan,
SIZE_OF_ARRAY(dulieu.tentaikhoan), const char*
dulieu.taikhoankhac,
SIZE_OF_ARRAY(dulieu.taikhoankhac));
if (flag == 0)
{
cout << "Ten nay cua ban chua duoc dang ky, ban
co muon dang ky? Y/N" << endl;
char yesorno = _getch();
if (yesorno == y)
{
goto case 2;
}
else(yesorno == n)
{
cout << "vui long an enter de quay lai" <<
endl;
goto case 1;
}
}
}
}
cout << endl;
cout << "Nhap mat khau: " << endl;
for (int b, b < 16, b++)
{
dulieu.matkhau[b] = _getch();
}
getline()//this is where i need to compare passwords?
int array_equal(const char* array1, size_t size1, const char*
array2, size_t size2);
if (flag == 0)
{
cout << "Sai mat khau" << endl;
continue;
}
else (flag == 1)
{
cout << "Chao mung " << dulieu.tentaikhoan << endl;
}
case 2:
cout << "Nhap ten tai khoan: " << endl;
for (int c, c < 20, c++)
{
dulieu.tentaikhoan[c] = _getch();
}
cout << endl;
int array_equal(const char* array1, size_t size1, const char*
array2, size_t size2);
if (flag == 0)
{
cout << "Ten tai khoan da co nguoi chon" << endl;
continue;
}
else (flag == 1)
{
cout << "Nhap mat khau" << endl;
for (int d, d < 16, d++)
{
dulieu.matkhau[d] = _getch();
}
}
cout << "Chao mung " << dulieu.tentaikhoan << endl;
}
}
as for array_equal heres the code
int array_equal(const char* array1, size_t size1, const char*
array2, size_t size2) {
int flag = 1;
assert(array1 != NULL);
assert(array2 != NULL);
assert(size1 != 0);
assert(size2 != 0);
if (size1 != size2) return flag = 0;
for (size_t i = 0; i < size1; ++i) {
if (array1[i] != array2[i]) return flag = 0;
}
return flag;
}
If you want to proceed forward with your implementation, you likely want to use the modulo operator (%).
However, I would recommend using a csv format as you stated:
username,password
sally,pass1
bob,passwd2
joe,passwd3
Steps to make CSV work:
Open the file: fopen()
Readline by line: getline()
Check if entered username exists within the line. Something like std::string:;substr() would definately do the job
If matches, then compare passwd
Do w/e needed if username and passwd are correct
close file: close()

Multiple file project & Function in C++

I am trying to practice the multiple file project (creating .cpp files and also .h files) and functions together.I have some functions for different kinds of shapes which is in different .cpp files and a .h file (my Functions.h) with the prototypes of those functions. I created another .cpp file (tools.cpp) where I have all bunch of functions (such as- getInt, getFloat, getBool, getBoundedInt, getWidth etc) so that I can also use that one in my other projects as well and also for that tools.cpp file. I have tools.h file with the prototypes.
Now, I want to make another function (allFunctionController) which will handle all these different kinds of function (like- taking user input, checking input valid or invalid, help function for user, call the shape functions etc). And, there would be another function to allow user to repeat all these things and my main function will only call this one. The screenshot that I provided would be more clear to understand.
[screenshot]
tools.cpp :-
// Tools.cpp
#include"Tools.h"
#include<string>
#include<iostream>
using namespace std;
namespace tools
{
int width( int value )
{
bool isNegative = value < 0;
int spaceForSign;
if ( isNegative )
{
spaceForSign = 1;
value = -value;
}
else
spaceForSign = 0;
int digitCount = 0;
int digits = value;
do
{
// pull one digit off and count it;
++digitCount;
// if I wanted to look at the digit before throwing away:
int digit = digits % 10;
digits = digits / 10; // remove one digit
} while ( digits > 0 );
return digitCount;
}
char getChar(string prompt)
{
while (true)
{
char userInput;
cout << prompt;
cin >> userInput;
cin.ignore(999,'\n');
if ( !cin.fail() ) return userInput;
cin.clear();
cin.ignore(999,'\n');
cout << "try again" << endl;
}
}
int getInt(string prompt)
{
while (true)
{
int userInput;
cout << prompt;
cin >> userInput;
cin.ignore(999,'\n');
if ( !cin.fail() ) return userInput;
cout << "input failure, try again";
cin.clear();
cin.ignore(999,'\n');
}
}
int getBoundedInt( string prompt, int lowBound, int highBound )
{
while (true)
{
int userInput = getInt(prompt);
if ( lowBound <= userInput && userInput <= highBound )
return userInput;
cout << "must be in range " << lowBound << " to "
<< highBound << ", try again" << endl;
}
}
float getFloat(string prompt)
{
while (true)
{
float userInput;
cout << prompt;
cin >> userInput;
cin.ignore(999,'\n');
if ( !cin.fail() ) return userInput;
cout << "input failure, try again";
cin.clear();
cin.ignore(999,'\n');
}
}
string getString(string prompt)
{
while (true)
{
string userInput;
cout << prompt;
cin >> userInput;
cin.ignore(999,'\n');
if ( !cin.fail() ) return userInput;
cout << "input failure, try again";
cin.clear();
cin.ignore(999,'\n');
}
}
string getLine(string prompt)
{
while (true)
{
string userInput;
cout << prompt;
getline(cin, userInput);
if ( !cin.fail() ) return userInput;
cout << "input failure, try again";
cin.clear();
cin.ignore(999,'\n'); // whatever caused fail
}
}
bool isLowerCase( char c )
{
return 'a' <= c && c <= 'z';
}
bool isUpperCase( char c )
{
return 'A' <= c && c <= 'Z';
}
bool isLetter( char c )
{
return isLowerCase(c) || isUpperCase(c);
}
char getLetter(string prompt)
{
while (true)
{
char userInput = getChar(prompt);
if ( isLetter(userInput) )
return userInput;
cout << "letters only, please" << endl;
}
}
bool getBool(string prompt)
{
while (true)
{
switch ( getChar(prompt) )
{
case 'y': case 'Y': return true;
case 'n': case 'N': return false;
}
cout << "y or n please" << endl;
}
}
}
tools.h:-
// Tools.h
#ifndef TOOLS_LOCK
#define TOOLS_LOCK
#include<string>
namespace tools
{
int getInt(std::string prompt);
int width( int value );
char getChar(std::string prompt);
int getInt(std::string prompt);
int getBoundedInt( std::string prompt, int lowBound, int highBound );
float getFloat(std::string prompt);
std::string getString(std::string prompt);
std::string getLine(std::string prompt);
bool isLowerCase( char c );
bool isUpperCase( char c );
bool isLetter( char c );
char getLetter(std::string prompt);
bool getBool(std::string prompt);
}
#endif
My functions.h:-
// My functions.h
namespace myFunctions
{
void allFunctionController ();
void solidRectangle (int size);
void hollowRectangle (int userChoiceOfSize);
void solidTriangleFacingNorthEast (int size);
void hollowTriangleFacingNorthEast (int size);
void solidTriangleFacingSouthWest (int size);
void hollowTriangleFacingSouthWest (int size);
}
I am only adding here the hollow and solid rectangle code. But there are more shape function in my project.
hollowRectangle.cpp:-
#include"My functions.h"
#include<iostream>
using namespace std;
namespace myFunctions
{
void hollowRectangle (int size)
{
int row, column;
for (row = 1; row <= size; row++)
{
if (row > 1 && row < size)
{
cout << "*";
for (column = 2; column < size; column++)
{
cout << ' ';
}
cout << "*";
}
else
{
for (column = 1; column <= size; column++)
{
cout << "*";
}
}
}
cout << endl;
cout << endl;
cout << "Please press enter to finish...";
cin.ignore(999,'\n');
return;
}
}
solidRectangle.cpp:-
// Program for the solid rectangle
#include"My functions.h"
#include<iostream>
using namespace std;
namespace myFunctions
{
int solidRectangle (int size)
{
int row, column;
for (row = 1; row <= size; row++)
{
for (column = 1; column <= size; column++)
{
cout << "*";
}
cout << endl;
}
cout << endl;
cout << "Please press enter to finish...";
cin.ignore(999,'\n');
return 0;
}
}
allFunctionController:- I screwed up here.
// This function will control all other functions.
#include"My functions.h"
#include"Tools.h"
#include<iostream>
using namespace std;
void allFunctionController ()
{
using namespace tools;
{
int size = getBoundedInt ("Please enter the size", 1, 75);
}
}
using namespace myFunctions;
{
void getHelp ()
{
int size,userInput;
cin >> userInput;
switch (userInput)
{
case 1:
solidRectangle (size);
}
}
}
I want to know how to handle all these header files and use the function in my allFunctionController function.
I didn't write my main function yet. Please let me know if there is anything wrong in my posting either code or attachment. Thanks in advance.

Why does my program skip the first function? (Beginner C++)

I don't understand why getAges is being skipped.
#include <iostream>
#include <cctype>
using namespace std;
int getAges(int age, const int SIZE);
char getChoice();
void displayInOrder(int numbers[], const int SIZE, char choice);
void displayInReverse(int numbers[], const int SIZE, char choice);
int main()
{
const int SIZE = 5;
int numbers[SIZE] = { 1, 2 ,3 ,4, 5 };
char answer;
int age;
char choice;
if (toupper(choice) == 'O')
{
displayInOrder(numbers, SIZE, choice);
}
else if (toupper(choice) == 'R')
{
displayInReverse(numbers, SIZE, choice);
}
else
{
cout << "Invalid entry! - Must be O or R\n\n";
}
if (toupper(answer) == 'Y')
{
system("cls");
age = getAges(age, SIZE);
choice = getChoice();
displayInOrder(numbers, SIZE, choice);
displayInReverse(numbers, SIZE, choice);
cout << "Run program again (Y or N)? ";
cin >> answer;
break;
}
else if (toupper(answer) == 'N')
{
return 0;
}
return 0;
}
int getAges(int age, const int SIZE)
{
cout << "Enter " << SIZE << " ages: \n\n";
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
return age;
}
char getChoice()
{
char choice;
cout << "How do you want to see the ages displayed? \n\n Enter O for In Order, or R for In Reverse.\n\n";
cin >> choice;
return choice;
}
void displayInOrder(int numbers[], const int SIZE, char answer)
{
cout << "Here are the ages in order: \n\n";
for (int i = 0; i < SIZE; i++)
{
cout << numbers[i] << endl;
}
}
void displayInReverse(int numbers[], const int SIZE, char answer)
{
cout << "Here are the ages in reverse order: \n\n";
for (int i = SIZE - 1; i >= 0; i--)
{
cout << numbers[i] << endl;
}
}
I started working on this before the OP updated the title to their original question about "while loops & break statements". However at the time I came across this question the OP had originally removed the while loops. I was looking over the provided functions to get an idea of what the OP was trying to do and this is what I have come up with.
First: while loops are exactly what you want here, but you want a specific type of while loop, a do-while loop in this case.
Next: There is no need for break statements if you know how to structure your do-while loop correctly.
Finally: I made some modifications to the OP's existing functions by changing or removing unnecessary parameter(s), return type(s) & code duplication. I removed a function that was no longer needed. I changed the output formatting of the messages to display a clean looking program. I also removed a bad practice of having using namespace std; in the global scope.
I did this to demonstrate to the OP how a while loop can be constructed without the need of break statements and that they were originally on the right track but needed a little bit of assistance to get on their way.
Here is the source code to a working program on what I think the OP was aiming to do.
#include <iostream>
#include <cctype>
void getAge( int& age );
void displayInOrder( int numbers[], const int SIZE);
void displayInReverse( int numbers[], const int SIZE );
int main() {
const int SIZE = 5;
int numbers[SIZE] = { 0 };
char answer = '\0';
int age = 0;
char choice = '\0';
std::cout << "========================================================================\n"
<< "This program will have the user enter in "
<< SIZE
<< " Ages. \nThen ask the user in which order to display the list of ages.\n"
<< "Finally the program will ask the user if they want to continue or not.\n"
<< "========================================================================\n\n";
do {
for ( int i = 0; i < SIZE; i++ ) {
getAge( age );
numbers[i] = age;
}
std::cout << "\nPlease enter 'O' for ordered or 'R' for reversed list.\n";
std::cin >> choice;
if ( toupper( choice ) == 'O' ) {
displayInOrder( numbers, SIZE );
}
if ( toupper( choice ) == 'R' ) {
displayInReverse( numbers, SIZE );
}
std::cout << "\nDo you want to run program again (Y/N)?";
std::cin >> answer;
} while ( toupper( answer ) == 'Y' );
return 0;
}
void getAge( int& age ) {
int temp;
std::cout << "Enter an age: \n";
std::cin >> temp;
age = temp;
}
void displayInOrder( int numbers[], const int SIZE ) {
std::cout << "\nHere are the ages in order: \n";
for ( int i = 0; i < SIZE; i++ ) {
std::cout << numbers[i] << std::endl;
}
}
void displayInReverse( int numbers[], const int SIZE ) {
std::cout << "\nHere are the ages in reverse order: \n";
for ( int i = SIZE - 1; i >= 0; i-- ) {
std::cout << numbers[i] << std::endl;
}
}

How to fix this code

Please, how to fix this code
[Error] a function-definition is not allowed here before '}' token
[Error] expected '}' at the end of input
I don't know what's the problem with my code even though I've already checked the compiler errors
#include<iostream>
using namespace std;
struct name_type
{
string first,middle,last;
};
struct SD
{
name_type name;
float grade;
};
const int MAX_SIZE = 35;
int isFull(int last) {
if(last == MAX_SIZE - 1) {
return(1);
}
else {
return(0);
}
}
int isEmpty(int last) {
if(last < 0) {
return(1);
}
else {
return(0);
}
}
main()
{
SD SD2[MAX_SIZE];
int last = -1;
if(isEmpty(last))
{
cout << "List is empty\n";
}
for (int a=0; a <35; a++)
{
cout << "Enter first name:.....";
cin >> SD2[a].name.first;
cout << "Enter middle name:....";
cin >> SD2[a].name.middle;
cout << "Enter last name:......";
cin >> SD2[a].name.last;
cout << "Enter your grade:.....";
cin >> SD2[a].grade;
cout << '\n';
}
system("cls");
cout << "1 - Add";
cout << "2 - Delete";
cout << "3 - Search";
cout << "4 - Print";
cout << "5 - Exit";
string lname, fname;
int choice, search;
cin >> choice;
if(choice == 3) {
cin >> fname;
cin >> lname;
int index = search;
(SD2, lname, fname, last);
if (index > 0) {
cout << "ERROR\n";
}
else {
cout << "The grade of " << lname << "," << fname << "is " << SD2[index].grade;
}
}
int search(SD list [], string search_lname, string search_fname, int last) {
int index;
if(isEmpty(last)==1) {
cout << "\nThe list is Empty!";
}
else {
index = 0;
while(index!= last+1 && list[index].name.first != search_fname && list[index].name.last != search_lname) {
++index;
}
if(index != last + 1) {
cout << "\nItem Requested is Item" << index + 1 << ".";
return index;
}
else {
cout << "\n Item Does Not Exist.";
}
}
return -1; // list is empty or search item does not exist
}
}
One of the problems is in your declaration of the main function:
main()
In c++, the main() function must have a return type of int. Sin you have not specified any data type for the return value of main(), it sets the return data type to void, which is produces the error just before main(). To learn and understand more about main() for C++, visit the following link Main Function.
To sort this, change the above line of code to:
int main() // notice that the return type here is int. This is required in c++
Another thing: in these lines:
int index = search;
(SD2, lname, fname, last);
Over here, you want to pass SD2, lname, fname and last to the search() function. However, your syntax is wrong. The function and its parameters when called cannot be split by a semicolon, because a semicolon terminates the statement. Therefore, the compiler sees search as a variable, not a function. This along with the statement following it cause the error. You should change those 2 lines to:
int index = search(SD2, lname, fname, last); // this is proper syntax to call a function.
Also, you need to take out search() from inside the main() function and place it above the main() function. That is also causing an error.