How to use main variable in functions? - c++

I got a function but i can't define any variable inside and global too. This function gets a char value from user. I need to define this value to main function. How can i do it? Thanks for helping guys.
This is my code. I made it like this but I define variables in global but I need to define this variables in only main.
#include <iostream>
using namespace std;
char cName[255], cSurname[255];
bool nameFunc() {
cout << "Whats Your Name ?\n";
cin >> cName;
if (cName != NULL && cName[0] == '\0') {
return false;
}
else {
return true;
}
}
bool surnameFunc() {
cout << "Whats Your Surname ?\n";
cin >> cSurname;
if (cSurname != NULL && cSurname[0] == '\0') {
return false;
}
else {
return true;
}
}
int main() {
if (nameFunc() and surnameFunc()) {
cout << "Hello, " << cName << " " << cSurname << "." << endl;
}
else {
cout << "Error! Name or Surname is empty." << endl;
}
system("PAUSE");
return 0;
}

You could pass references to your variables to the functions. Since the char[] have a fixed length, you need to make sure that you don't write out-of-bounds which complicates things.
Example:
#include <iostream>
template<size_t N>
bool nameFunc(char (&cName)[N]) {
std::cout << "Whats Your Name ?\n";
std::cin.getline(cName, N); // read at most N chars
return cName[0] != '\0';
}
template<size_t N>
bool surnameFunc(char (&cSurname)[N]) {
std::cout << "Whats Your Surname ?\n";
std::cin.getline(cSurname, N); // read at most N chars
return cSurname[0] != '\0';
}
int main() {
char cName[255], cSurname[255];
if (nameFunc(cName) and surnameFunc(cSurname)) {
std::cout << "Hello, " << cName << " " << cSurname << ".\n";
}
else {
std::cout << "Error! Name or Surname is empty.\n";
}
}
A much easier option would be to use std::strings and pass them by reference to the functions.

Is it what you're looking for?
#include <iostream>
using namespace std;
bool nameFunc(char* cName) {
cout << "Whats Your Name ?\n";
cin >> cName;
if (cName != NULL && cName[0] == '\0') {
return false;
}
else {
return true;
}
}
bool surnameFunc(char* cSurname) {
cout << "Whats Your Surname ?\n";
cin >> cSurname;
if (cSurname != NULL && cSurname[0] == '\0') {
return false;
}
else {
return true;
}
}
int main() {
char cName[255], cSurname[255];
if (nameFunc(cName) and surnameFunc(cSurname)) {
cout << "Hello, " << cName << " " << cSurname << "." << endl;
}
else {
cout << "Error! Name or Surname is empty." << endl;
}
system("PAUSE");
return 0;
}

Related

Two codes; same logic and line of code, one works but other doesn't

I asked this question a couple of hours ago; I want to see if someone can now explain the problem.
One code is about separating items in a grocery; in the end you'll have two(2) bags; a fragileBag and a normalBag.
Other code separates passengers depending on the office they go for pickup; in the end you'll have three(3) types of passengers; ones that go to rio, ones that go to maya, and ones that request elsewhere.
Both codes use the same logic but the passenger code gives an error on a line that works perfectly on the grocery code.
Just to be clear, BOTH CODES RETURN VALUES OF STRING.
ERROR FROM THE PASSENGER CODE:
Error (active) E0304 no instance of overloaded function "std::vector<_Ty,_Alloc>::push_back [with _Ty=trans, _Alloc=std::allocator<trans>]" matches the argument list dataPractice2 C:\Users\javye\source\repos\dataPractice2\dataPractice2\main.cpp 82
and also:
Error C2664 'void std::vector<trans,std::allocator<_Ty>>::push_back(_Ty &&)': cannot convert argument 1 from 'std::string' to 'const _Ty &' dataPractice2 c:\users\javye\source\repos\datapractice2\datapractice2\main.cpp 82
//GROCERY FUNCTION
//separate function
void separateItems(vector<myBag>& newMyVector) {
for (int x = newMyVector.size() - 1; x >= 0; --x) {
if (newMyVector[x].getItem() == "eggs" || newMyVector[x].getItem() == "bread") {
fragileBag.push_back(newMyVector[x].getItem()); //NO PROBLEM HERE
newMyVector.pop_back();
}
else {
normalBag.push_back(newMyVector[x].getItem()); //OR HERE
newMyVector.pop_back();
}
}
}
//PASSENGER FUNCTION
//separate function
void separateP(vector<trans>& newMyVector) {
for (int x = newMyVector.size() - 1; x >= 0; --x) {
if (newMyVector[x].getXoLoc() == "rio") {
rioLoc.push_back(newMyVector[x].getXoLoc()); //PROBLEM HERE
newMyVector.pop_back();
}
else
if (newMyVector[x].getXoLoc() == "maya") {
mayaLoc.push_back(newMyVector[x].getXoLoc()); //HERE
newMyVector.pop_back();
}
else
elseLoc.push_back(newMyVector[x].getXoLoc()); //HERE
newMyVector.pop_back();
}
}
//GROCERY FULL CODE
//HEADER
#pragma once
#include<iostream>
#include<vector>
#include<string>
using namespace std;
#ifndef BAG_H
#define BAG_H
class myBag {
public:
myBag(); //default constructor
myBag(string anItemName); //overload constructor
void addItem(string anItemName); //mutator
string getItem();//accessor
private:
string itemName;
};
#endif
//SOURCE
#include"bag.h"
myBag::myBag() {
addItem("");
}
myBag::myBag(string anItemName) {
addItem(anItemName);
}
void myBag::addItem(string anItemName) {
itemName = anItemName;
}
string myBag::getItem() {
return itemName;
}
//MAIN
#include"bag.h"
void inputItems(vector<myBag>&); //input data function prototype
void displayQuantity(vector<myBag>&); //display data function prototype
void separateItems(vector<myBag>&); //function that separates items; func prototype
void fragBag(vector<myBag>&); //fragile bag function prototype
void norBag(vector<myBag>&); //normal bag function prototype
vector<myBag> myVector; //main vector
vector<myBag> fragileBag, normalBag; //seconday vectors
string item; //global item variable
int main() {
int option;
try {
do {
cout << "\tMENU"
<< endl << "1) Input Items"
<< endl << "2) Display Quantity"
<< endl << "3) Separate (IMPORTANT)"
<< endl << "4) Display Items in Fragile Bag"
<< endl << "5) Display Items in Normal Bag"
<< endl << "6) Exit Program"
<< endl << endl << "Choose: ";
cin >> option;
if (option > 6) {
throw 404;
}
switch (option) {
case 1: //input
system("cls");
inputItems(myVector);
system("pause");
system("cls");
break;
case 2://display
system("cls");
displayQuantity(myVector);
system("pause");
system("cls");
break;
case 3: //separate
system("cls");
separateItems(myVector);
system("pause");
system("cls");
break;
case 4: //fragile
system("cls");
fragBag(myVector);
system("pause");
system("cls");
break;
case 5: //normal
system("cls");
norBag(myVector);
system("pause");
system("cls");
break;
case 6: //exit
exit(0);
}
} while (option != 6);
}
catch(int x){
cout << "ERROR, OPTION DOESN'T EXITS" << endl;
system("pause");
}
}
//input function
void inputItems(vector<myBag>& newMyVector) {
do {
cout << "Enter grocery items || enter letter X to stop: ";
cin >> item;
if (item != "x")
newMyVector.push_back(myBag(item));
} while (item != "x");
}
//display function
void displayQuantity(vector<myBag>& newMyVector) {
try {
for (int x = 0; x < newMyVector.size(); ++x) {
if (x == 0) {
cout << "Store bag has " << newMyVector.size() << " items in it. These are: " << endl;
}
cout << newMyVector[x].getItem() << endl;
}
if (newMyVector.empty())
throw 404;
}
catch (int x) {
cout << "ERROR " << x << " ,QUANTITY NOT FOUND" << endl;
}
}
//separate function
void separateItems(vector<myBag>& newMyVector) {
for (int x = newMyVector.size() - 1; x >= 0; --x) {
if (newMyVector[x].getItem() == "eggs" || newMyVector[x].getItem() == "bread") {
fragileBag.push_back(newMyVector[x].getItem()); //PROBLEM WOULD APPEAR HERE, BUT DOESN'T, UNLIKE THE OTHER CODE
newMyVector.pop_back();
}
else {
normalBag.push_back(newMyVector[x].getItem());
newMyVector.pop_back();
}
}
}
//fragile bag function
void fragBag(vector<myBag>& newMyVector) {
try {
for (int x = 0; x < fragileBag.size(); ++x) {
if (x == 0) {
cout << "The fragile bag has " << fragileBag.size() << " items in it. These are: " << endl;
}
cout << fragileBag[x].getItem() << endl;
}
if (fragileBag.empty()) {
throw 404;
}
}
catch (int x) {
cout << "ERROR " << x << " ,FRAGILE BAG EMPTY" << endl;
}
}
//normal bag function
void norBag(vector<myBag>& newMyVector) {
try {
for (int x = 0; x < normalBag.size(); ++x) {
if (x == 0) {
cout << "The normal bag has " << normalBag.size() << " items in it. These are: " << endl;
}
cout << normalBag[x].getItem() << endl;
}
if (normalBag.empty()) {
throw 404;
}
}
catch (int x) {
cout << "ERROR " << x <<" , NORMAL BAG EMPTY" << endl;
}
}
//PASSENGER FULL CODE
//HEADER
#pragma once
#include<iostream>
#include<vector>
#include<string>
using namespace std;
#ifndef TRANSPORT_H
#define TRANSPORT_H
class trans {
public:
trans();
trans(string aName, string anXoLoc, string anXfLoc, string aTime, string aCellNum);
void setName(string aName);
void setXoLoc(string anXoLoc);
void setXfLoc(string anXfLoc);
void setTime(string aTime);
void setCellNum(string aCellNum);
string getName();
string getXoLoc();
string getXfLoc();
string getTime();
string getCellNum();
private:
string name;
string xoLoc; //offices
string xfLoc; //destination
string time;
string cellNum;
};
//SOURCE
#include"transport.h"
trans::trans() {
setName("");
setXoLoc("");
setXfLoc("");
setTime("");
setCellNum("");
}
trans::trans(string aName, string anXoLoc, string anXfLoc, string aTime, string aCellNum) {
setName(aName);
setXoLoc(anXoLoc);
setXfLoc(anXfLoc);
setTime(aTime);
setCellNum(aCellNum);
}
void trans::setName(string aName) {
name = aName;
}
void trans::setXoLoc(string anXoLoc) {
xoLoc = anXoLoc;
}
void trans::setXfLoc(string anXfLoc) {
xfLoc = anXfLoc;
}
void trans::setTime(string aTime) {
time = aTime;
}
void trans::setCellNum(string aCellNum) {
cellNum = aCellNum;
}
string trans::getName() {
return name;
}
string trans::getXoLoc() {
return xoLoc;
}
string trans::getXfLoc() {
return xfLoc;
}
string trans::getTime() {
return time;
}
string trans::getCellNum() {
return cellNum;
}
#endif
//MAIN
#include"transport.h"
void inputInfo(vector<trans> &);
void displayInput(vector<trans>&);
void separateP(vector<trans>&);
void rio(vector<trans>&);
void maya(vector<trans>&);
void elsewhere(vector<trans>&);
vector<trans> myVector;
vector<trans> rioLoc, mayaLoc, elseLoc;
string newName;
string newXoLoc; //offices
string newXfLoc; //destination
string newTime;
string newCellNum;
//main not ready. Creating each function one by one to them make it look nice
int main() {
int option;
do {
cout << "MENU"
<< endl << "1) input "
<< endl << "2) output "
<< endl << "3) separate"
<< endl << "4) rio passengers"
<< endl << "5) maya passengers"
<< endl << "6) elsewhere passengers";
cin >> option;
switch(option){
case 1:
inputInfo(myVector);
break;
case 2:
displayInput(myVector);
break;
case 3:
separateP(myVector);
break;
case 4:
rio(myVector);
break;
case 5:
maya(myVector);
break;
case 6:
elsewhere(myVector);
break;
case 7:
exit(0);
}
} while (option != 7);
system("pause");
}
void inputInfo(vector<trans> &newMyVector) {
int charSize;
cout << "How many passangers to register: ";
cin >> charSize;
for (int x = 0; x < charSize; ++x) {
cout << "Name of passanger: ";
cin >> newName;
cout << "Office: ";
cin >> newXoLoc;
cout << "Destination: ";
cin >> newXfLoc;
cout << "Time of pickup: ";
cin >> newTime;
cout << "Cellphone: ";
cin >> newCellNum;
if (charSize != 0)
newMyVector.push_back(trans(newName, newXoLoc, newXfLoc, newTime, newCellNum));
}
}
void displayInput(vector<trans>& newMyVector) {
for (int x = 0; x < newMyVector.size(); ++x) {
if (x == 0) {
cout << "There are " << newMyVector.size() << " passengers. These are: " << endl;
}
cout << "-----------------------------Passenger #" << x + 1 << endl;
cout << newMyVector[x].getName() << endl;
cout << newMyVector[x].getXoLoc() << endl;
cout << newMyVector[x].getXfLoc() << endl;
cout << newMyVector[x].getTime() << endl;
cout << newMyVector[x].getCellNum() << endl;
}
}
void separateP(vector<trans>& newMyVector) {
for (int x = newMyVector.size() - 1; x >= 0; --x) {
if (newMyVector[x].getXoLoc() == "rio") {
rioLoc.push_back(newMyVector[x]);
newMyVector.pop_back();
}
else
if (newMyVector[x].getXoLoc() == "maya") {
mayaLoc.push_back(newMyVector[x]);
newMyVector.pop_back();
}
else
elseLoc.push_back(newMyVector[x]);
newMyVector.pop_back();
}
}
void rio(vector<trans>& newMyVector) {
for (int x = 0; x < rioLoc.size(); ++x) {
if (x == 0) {
cout << "Num. of passangers to pickup in Rio Piedras is " << rioLoc.size() << " , these are: " << endl;
}
cout << rioLoc[x].getName() << endl;
cout << rioLoc[x].getXoLoc() << endl;
cout << rioLoc[x].getXfLoc() << endl;
cout << rioLoc[x].getTime() << endl;
cout << rioLoc[x].getCellNum() << endl;
}
}
void maya(vector<trans>& newMyVector) {
for (int x = 0; x < mayaLoc.size(); ++x) {
if (x == 0) {
cout << "Num. of passangers to pickup in Mayaguez is " << mayaLoc.size() << " , these are: " << endl;
}
cout << mayaLoc[x].getName() << endl;
cout << mayaLoc[x].getXoLoc() << endl;
cout << mayaLoc[x].getXfLoc() << endl;
cout << mayaLoc[x].getTime() << endl;
cout << mayaLoc[x].getCellNum() << endl;
}
}
void elsewhere(vector<trans>& newMyVector) {
for (int x = 0; x < elseLoc.size(); ++x) {
if (x == 0) {
cout << "Num. of passangers to pickup in elsewhere is " << elseLoc.size() << " , these are: " << endl;
}
cout << elseLoc[x].getName() << endl;
cout << elseLoc[x].getXoLoc() << endl;
cout << elseLoc[x].getXfLoc() << endl;
cout << elseLoc[x].getTime() << endl;
cout << elseLoc[x].getCellNum() << endl;
}
}
To explain why the second code does not work I first have to explain why the first code appears to work.
myBag::myBag(string anItemName)
can make a bag out of a string. It is a Conversion Constructor. So when
fragileBag.push_back(newMyVector[x].getItem());
is compiled, the compiler quietly inserts a call to the myBag(string) constructor and you get something more like
fragileBag.push_back(myBag(newMyVector[x].getItem()));
which makes no sense logically. It says turn an item in a bag into a bag with one item and insert this new bag into still another bag, fragileBag.
When you look more closely at myBag, you see that it isn't a bag at all. It is a single item and should be renamed to myItem or discarded all together in favour of an all-new all-different myBag that is a wrapper around a vector of string where the strings represent items. This makes
myBag fragileBag;
the real bag.
In other words, the only reason the working code works is it doesn't actually do what the naming implies it does. The code compiles and produces the expected result, but is semantically troubled.
This leads to the confusion with
rioLoc.push_back(newMyVector[x].getXoLoc());
rioLoc is a vector<trans> and can only hold trans. There is no trans::trans(string) to convert a string to a trans so the faulty logic of the grocery code is exposed. As bag and item have been intertwined in grocery, passenger and transport are combined here.
The fix for grocery described above is relatively straight forward. Passenger will need a slightly different solution with both a passenger class to describe the passengers and a transport class to describe the means of transport. transport will have a vector<passenger> member to contain its passengers as well as methods to add and remove the passengers and possibly book-keeping to track the location of the transport, details incompletely specified by the question.
Both codes are pushing string values into a vector that does not hold string values.
Your grocery code uses a vector of myBag objects. The code works because myBag has a non-explicit constructor that takes a single string as input, so the compiler is able to implicitly construct a temporary myBag object to push into the vector.
Your passenger code uses a vector of trans objects. The code fails because trans does not have a constructor that takes a single string as input, so the compiler cannot construct a temporary trans to push into the vector.

function already has a body and redefinition of string variable

ERRORS:
error messages
mainFun.cpp:
#include <iostream>
#include <string>
#include "userCheckFunH.h"
using namespace std;
int yesNo;
string passName;
string userName;
string userRetrieve()
{
if (userName == "")
{
cin >> userName;
}
else
{
if (userName == "devin772" || userName == "guestacc")
{
yesNo = 1;
}
else
{
yesNo = 0;
}
}
return userName;
}
int userCheck()
{
return yesNo;
}
int main()
{
do
{
string userN;
system("cls");
// ui
cout << " DH DB " << endl;
cout << "x----------------x" << endl;
//username
cout << "username: " << endl;
cout << "> ";
// fun call
userRetrieve();
int continueP = userCheck();
cout << "" << endl;
// password
if (continueP = 1 && userRetrieve() == "devin772")
{
cout << "password:" << endl;
cout << "> ";
cin >> passName;
if (passName == "12qwaszx")
{
cout << "" << endl;
system("pause");
system("cls");
// run program
dataBaseRunP("admin");
npOpen();
cout << "" << endl;
system("pause");
return 0;
}
}
else if (continueP = 1 && userRetrieve() == "guestacc")
{
cout << "password:" << endl;
cout << "> ";
cin >> passName;
if (passName == "guestguest")
{
cout << "" << endl;
system("pause");
system("cls");
// run program
dataBaseRunP("regUser");
npOpen();
cout << "" << endl;
system("pause");
return 0;
}
}
else
{
cout << "Invalid username." << endl;
cout << "" << endl;
system("pause");
userRetrieve() = "";
userName = "";
yesNo = 0;
passName = "";
}
} while (true);
system("pause");
}
nextFun.cpp :
#include <iostream>
#include "userCheckFunH.h"
using namespace std;
string userLevel;
int dataBaseRunP(string authLevel)
{
string fileName;
if (authLevel == "regUser")
{
fileName = "user.txt";
userLevel = fileName;
}
else if (authLevel == "admin")
{
fileName = "admin.txt";
userLevel = fileName;
}
else
{
cout << "ERROR - user level not found." << endl;
system("pause");
exit(EXIT_FAILURE);
return 0;
}
exit(EXIT_SUCCESS);
return 0;
}
void npOpen()
{
string fileNpName;
fileNpName = userLevel;
fileNpName = "notepad \"" + fileNpName + "\"";
system(fileNpName.c_str());
}
userCheckFunH.h:
#ifndef USERCHECKFUN_H
#define USERCHECKFUN_H
#include "nextFun.cpp"
int dataBaseRunP();
void npOpen();
#endif
i'm attempting to make a basic program that allows you to open files hidden through windows in a basic c++ program. keep getting this error. tried different header guards, variable names, function names, file names. i also delete nextFun.cpp and the program ran fine. i can't get past this error, please help.
thanks! :)
It is highly unusual to include a cpp file, which you do in userCheckFunH.h, with
#include "nextFun.cpp"
Your nextFun.cpp file includes this very header:
#include "userCheckFunH.h"
Since you cpp file doesn't have an include guard (which is fine) you end up with the functions in the cpp file twice.
Don't include the cpp file in the header.

C2664 cannot convert argument 1 from 'const char *' to 'Node*'

I'm writing a modified version of 20 Questions for my CS2 class and I am having one heck of a time trying to figure out why I'm getting the error.
IC2664 cannot convert argument 1 from 'const char ' to 'Node'
Anyways, any assistance would be appreciated.
#include "LetMeGuess.h"
#include<iostream>
#include<memory>
#include<string>
#include<fstream>
#include<vector>
struct LetMeGuess::Node {
Node(std::string data) : data(data), no(nullptr), yes(nullptr) {};
std::string data;
std::shared_ptr<Node>no;
std::shared_ptr<Node>yes;
};
void LetMeGuess::letMeGuess() {
std::cout << "***Let Me Guess!***\nLoading questionArchive.txt ..." << std::endl;
readInFile();
std::cout << "Done!" << std::endl;
askQuestions();
std::cout << "Saving questionArchive.txt ..." << std::endl;
readOutFile(root);
std::cout << "Done! Goodbye!" << std::endl;
}
void LetMeGuess::readInFile() {
root = std::shared_ptr<Node>("Is it an animal?");
root->no = std::shared_ptr<Node>("Toaster");
root->yes = std::shared_ptr<Node>("Elephant");
//std::vector<Node> myStack;
//std::shared_ptr<Node> newNode;
//std::string nextInfo;
//std::string nextID;
//fin.open("questionArchive.txt");
//while (!fin.eof) {
// fin >> nextID;
// if (nextID == "A") {
// fin >> nextInfo;
// Node newNode(nextInfo);
// myStack.push_back(newNode);
// }
// else {
// fin >> nextInfo;
// Node newNode = Node(nextInfo);
// Node newNode->yes = myStack.back();
// }
//}
}
std::string LetMeGuess::readOutFile(std::shared_ptr<Node>curr) {
curr = root;
std::string outString;
fout.open("questionArchive.txt");
if (!curr) return outString;
outString += readOutFile(curr->no);
outString += readOutFile(curr->yes);
if (curr->no == nullptr || curr->yes == nullptr) {
outString += "A ";
}
else {
outString += "Q ";
}
outString += curr->data;
outString += "/n";
fout << outString;
return outString;
}
bool LetMeGuess::stillAsking(std::shared_ptr<Node> temp){
if (temp->no == nullptr || temp->yes == nullptr) return false;
else return true;
}
bool LetMeGuess::playAgain(char ans) {
switch (ans) {
case'Y':
case'y':
return true;
case'N':
case'n':
default:
std::cout << "y/n not selected, starting a new game anyways." << std::endl;
return true;
}
}
void LetMeGuess::insertNewQuestion(std::shared_ptr<Node>& curr, std::string newQuest, std::string objThought) {
curr->no = std::make_shared<Node>(curr->data);
curr->yes = std::make_shared<Node>(objThought);
curr->data = newQuest;
}
void LetMeGuess::askQuestions() {
std::shared_ptr<Node> current = root;
char answer;
char plyAgn = 'y';
std::string thoughtObject;
std::string newQuestion;
while (playAgain(plyAgn)) {
while (stillAsking(current)) {
std::cout << current->data;
std::cin >> answer;
switch (answer) {
case'y':
case'Y':
current = current->yes;
break;
case'n':
case'N':
current = current->no;
break;
default:
std::cout << "Please enter y/n." << std::endl;
break;
}
}
std::cout << "Let me guess, you're thinking of a(n)" << current->data << "?" << std::endl;
std::cin >> answer;
switch (answer) {
case 'y':
case'Y':
std::cout << "I win!" << std::endl;
break;
case'n':
case'N':
std::cout << "What where you thinking of?" << std::endl;
std::cin >> thoughtObject;
std::cout << "What could I have asked to know you were thinking of a(n) " + thoughtObject + " and not a(n) " + current->data + "?" << std::endl;
std::cin >> newQuestion;
insertNewQuestion(current, newQuestion, thoughtObject);
break;
default:
std::cout << "Please enter y/n." << std::endl;
break;
}
std::cout << "Would you like to play again? (y/n)" << std::endl;
std::cin >> plyAgn;
}
}
root = std::shared_ptr<Node>("Is it an animal?");
root->no = std::shared_ptr<Node>("Toaster");
root->yes = std::shared_ptr<Node>("Elephant");
is incorrect way of creating shared_ptr .
root = std::make_shared<Node>("Is it an animal?");
root->no = std::make_shared<Node>("Toaster");
root->yes = std::make_shared<Node>("Elephant");
is the correct way of constructing shared_ptr

Function counting characters of a string class being skipped?

I was trying to count the number of characters in a string class but for some reason the program is skipping over my function completely. This is just the test code from the main program, it still was giving me the same results. How come the counter function is skipped over?
#include <iostream>
#include <string>
using namespace std;
void prompt(string& dna)
{
cout << "Input: ";
getline(cin, dna);
}
void counter(const string DNA,
int* a_count, int* t_count, int* c_count, int* g_count)
{
for (int i = 0; i < DNA.size(); i++)
{
if (DNA.at(i) == 'a')
{
*a_count++;
}
else if (DNA.at(i) == 't')
{
*t_count++;
}
else if (DNA.at(i) == 'c')
{
*c_count++;
}
else if (DNA.at(i) == 'g')
{
*g_count++;
}
}
}
int main()
{
string dna;
int a = 0;
int t = 0;
int c = 0;
int g = 0;
prompt(dna);
if (! dna.empty())
{
cout << "Before:\n"
<< "A: " << a << endl
<< "T: " << t << endl
<< "C: " << c << endl
<< "G: " << g << endl;
counter(dna, &a, &t, &c, &g);
cout << "\n\nAfter:\n"
<< "A: " << a << endl
<< "T: " << t << endl
<< "C: " << c << endl
<< "G: " << g << endl;
}
system("pause");
return 0;
}
You're applying operator ++ the wrong way. It should be:
if (DNA.at(i) == 'a')
{
(*a_count)++;
}
else if (DNA.at(i) == 't')
{
(*t_count)++;
}
else if (DNA.at(i) == 'c')
{
(*c_count)++;
}
else if (DNA.at(i) == 'g')
{
(*g_count)++;
}
You've got a priority problem between the ++ and * operators. You are incrementing the pointer address, not the value. (*a_count)++; would be correct.
You may find it easier to use reference parameters for the counts instead, since you don't actually need to do any pointer arithetic. ie:
void counter(const string DNA, int& a_count, int& t_count, int& c_count, int& g_count)
And, yes a switch statement would be neater.

C++ simple string replace, non complicated code, but producing crazy error

First, thank for you all your help!
The error I am getting is:
Unhandled exception at 0x7c812afb
(kernel32.dll) in Readerboard.exe:
Microsoft C++ exception:
std::out_of_range at memory location
0x0012f8a8..
I have found the problem to be with this line:
str.replace(str.find(sought), sought.size(), replacement);
It is located in this procedure:
void DisplayMessages() {
ifstream myReadFile;
string str;
static string myMessages[10];
static int i; // of course my famous i
static int MyPosition;
string sought;
string replacement;
myReadFile.open("C:\\Documents and Settings\\agerho000\\Desktop\\cms_export_test\\outages.htm",ios::in);
i = 0; //the start of my array
sought = "</td>"; // value that I want to replace with nothing
replacement.clear();
if(!myReadFile) // is there any error?
{
cout << "Error opening the file! Aborting…\n";
exit(1);
}
if (myReadFile.is_open())
{
cout << endl;
while (!myReadFile.eof())
{
getline(myReadFile, str);
if (str == "<tr>")
{
myReadFile.seekg(4,ios::cur);
getline(myReadFile, str);
str.replace(str.find(sought), sought.size(), replacement);
cout << str;
myMessages[i]=str;
i++;
}
}
}
i=0;
while (i < 10)
{
cout << i << ") " << myMessages[i] << endl;
i++;
if (myMessages[i]=="")
{
break;
}
}
myReadFile.close();
mainMenu();
}
The whole cpp file is displayed below:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void mainMenu();
void DisplayMessages();
void AddMessage();
void DeleteMessage();
void EditMessage();
void RunTests();
void CheckFile();
void CreateHtmlFile(string myMessages[10]);
/*
#define MIN 1
#define MAX 100
#define TRUE 1
#define FALSE 0
*/
int main() {
cout << endl;
cout << endl;
cout << "Hello Andrew.\n";
cout << "First you need some sort of menu.\n";
mainMenu();
return 0;
}
void mainMenu() {
int Command;
cout << endl;
cout << endl;
cout << endl;
cout << "What would you like to do?\n";
// cout << "1) Check that tests work!\n";
// cout << "2) Check that the file exists\n";
cout << "3) Display Messages\n";
// cout << "4) Edit a message\n";
// cout << "5) Add a message\n";
// cout << "6) Delete a message\n";
cout << "7) Exit\n";
cout << "Enter a number: ";
cin >> Command;
if (Command == 3)
{
DisplayMessages();
}
if (Command == 7)
{
cout << "Exiting...";
exit(EXIT_SUCCESS);
}
if (Command == 6)
{
DisplayMessages();
}
}
void DisplayMessages() {
ifstream myReadFile;
string str;
static string myMessages[10];
static int i; // of course my famous i
static int MyPosition;
string sought;
string replacement;
myReadFile.open("C:\\Documents and Settings\\agerho000\\Desktop\\cms_export_test\\outages.htm",ios::in);
i = 0; //the start of my array
sought = "</td>"; // value that I want to replace with nothing
replacement.clear();
if(!myReadFile) // is there any error?
{
cout << "Error opening the file! Aborting…\n";
exit(1);
}
if (myReadFile.is_open())
{
cout << endl;
while (!myReadFile.eof())
{
getline(myReadFile, str);
if (str == "<tr>")
{
myReadFile.seekg(4,ios::cur);
getline(myReadFile, str);
str.replace(str.find(sought), sought.size(), replacement);
cout << str;
myMessages[i]=str;
i++;
}
}
}
i=0;
while (i < 10)
{
cout << i << ") " << myMessages[i] << endl;
i++;
if (myMessages[i]=="")
{
break;
}
}
myReadFile.close();
mainMenu();
}
void AddMessage() {
}
/*
void DeleteMessage() {
ifstream myReadFile;
string str;
static string myMessages[10];
static int i; // of course my famous i
static int MyPosition;
string sought;
string replacement;
static int Command;
myReadFile.open("C:\\Documents and Settings\\agerho000\\Desktop\\cms_export_test\\outages.htm",ios::in);
i = 0; //the start of my array
sought = "</b></td>"; // value that I want to replace with nothing
replacement.clear();
if(!myReadFile) // is there any error?
{
cout << "Error opening the file! Aborting…\n";
exit(1);
}
if (myReadFile.is_open())
{
cout << endl;
while (!myReadFile.eof())
{
getline(myReadFile, str);
if (str == "<tr>")
{
myReadFile.seekg(7,ios::cur);
getline(myReadFile, str);
str.replace(str.find(sought), sought.size(), replacement);
myMessages[i]=str;
i++;
}
}
}
i=0;
while (i < 10)
{
cout << i << ") " << myMessages[i] << endl;
i++;
if (myMessages[i]=="")
{
break;
}
}
myReadFile.close();
cout << "Enter the number of the message you would like to delete?\n";
cout << "Or enter 11 to go back to the main menu.\n";
cin >> Command;
while (Command >= 12)
{
cout << "Invalid number, try again!\n";
cout << endl;
cout << "Enter the number of the message you would like to delete?\n";
cout << "Or enter 11 to go back to the main menu.\n";
cin >> Command;
}
if (Command == 11)
{
mainMenu();
}
myMessages[Command].clear();
//clear the string
//now rebuild the htm file with the new array
CreateHtmlFile(myMessages);
}
void EditMessage() {
}
void RunTests() {
}
void CheckFile() {
}
void CreateHtmlFile(string myMessages[])
{
}
//File.seekg(-5); moves the inside pointer 5 characters back
//File.seekg(40); moves the inside pointer 40 characters forward
//tellg() Returns an int type, that shows the current position of the inside-pointer for reading
//tellp() same as above but for writing
//seekp() just like seekg() but for writing
*/
Please help I am so stumped!
str.replace(str.find(sought), sought.size(), replacement); is wrong when str.find() doesn't find what it's looking for. str.find() will return str::npos, which will not be a valid location in the string. Hence, the call to replace fails with the index out of range exception you're seeing.
Change that to:
std::size_t foundIndex = str.find(sought);
if (foundIndex != str.npos)
str.replace(foundIndex, sought.size(), replacement);
else
std::cout << "Oops.. didn't find " << sought << std::endl;
and let us know if that helps you.
EDIT: You might also want to consider using boost::algorithm::replace_all from the Boost String Algorithms Library
A complete function for replacing strings:
std::string ReplaceString(std::string subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:
void ReplaceStringInPlace(std::string& subject, const std::string& search,
const std::string& replace) {
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos) {
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
Tests:
std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;
std::cout << "ReplaceString() return value: "
<< ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not modified: "
<< input << std::endl;
ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: "
<< input << std::endl;
Output:
Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def