Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm a beginner in C++ (4 days or so into my course) i created a small program that seems to work the way i want it to.
Quick summary:
The program asks for your name.
then asks for two numbers to add together.
displays the answer.
then asks if you want to calculate again y/n.
However, i can't help but feel like its a total train wreck in terms of formatting.
In particular the Again() function...
Inside of it, i created a loop by calling on another function if the condition was true. like so:
bool Again() {
std::cout << "Would you like to calculate again y/n?\n";
std::string answer = "";
std::cin >> answer;
if (answer[0] == 'y') {
std::cout << "Cool lets do it then \n";
PickTwo();
Again();
}
else {
std::cout << "alright, goodbye\n";
}
return 0;
}
Is it proper or improper to create a loop the way i did in Again() ?
if so, is there a right way to do it ?
This is the entire program:
#include <iostream>
#include <string>
void Greetings();
int PickTwo();
bool Again();
int main() {
Greetings();
PickTwo();
Again();
system("pause");
return 0;
}
void Greetings() {
std::cout << "Hi my name is Program, we're going to do something today. \n";
std::cout << "Whats your name?\n";
std::string Name;
std::getline(std::cin, Name);
std::cout << "Hi " << Name << ", we're going to try to do math\n";
return;
}
int PickTwo() {
std::cout << "Please pick the numbers to be added\n";
int firstNumber;
std::cin >> firstNumber;
int secondNumber;
std::cin >> secondNumber;
int Answer = firstNumber + secondNumber;
std::cout << "This are your numbers " << firstNumber << " and " << secondNumber << std::endl;
std::cout << "If we add them you have " << Answer << std::endl;
return Answer;
}
bool Again() {
std::cout << "Would you like to calculate again y/n?\n";
std::string answer = "";
std::cin >> answer;
if (answer[0] == 'y') {
std::cout << "Cool lets do it then \n";
PickTwo();
Again();
}
else {
std::cout << "alright, goodbye\n";
}
return 0;
}
Thank you in advance, knowing what NOT to do will help me fix the bad habits before they get worst.
Is it proper or improper to create a loop the way i did in Again() ? if so, is there a right way to do it ?
In a language that does not support tail recursion, your program has the potential to cause stack overflow. I would not recommend using it they way you have it coded.
It will be better to use a while loop or a do-while loop. In the loop, do whatever you need to do again.
Related
(I don't have much english vocabulary, so sry for this weird try of english)
Hi guys! I'm new at C++ and I need to know how to create a filter code that help me at only accept int-eger numbers. I need that this code use only the 'iostream' library. This is because my teacher don't let us use another kind of library (we are new at C++ coding).
Here I put an example of what I have at this moment:
# include <iostream>
# include <limits> //I should't use this library
using namespace std;
int main() {
int value = 0;
cout << "Enter an integer value: ";
while(!(cin >> value)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl <<"Value must be an integer"<< endl << endl; //This line needs <limits>
cout << "Enter another integer value: " ;
}
}
But this code have some inconvenients:
I'm using "#include 'limits'" library and I shouldn't use it
If you enter "1asd" it takes the "1" value, give it like if its correct and it isn't true
Do you guys have any solution for this situation? Thanks in advance for your time.
You just have to check if the bytes that the user entered are numerals like below. If all the bytes of the entered string are numerals (ie between characters 0 and 9), then the entire string is an integer. Except first byte of the string can be a '+', '-', a space/tab or just the first numeral in the number. (Thanks Zett42).
std::cout << "Enter an integer value: ";
std::string res1;
std::cin >> res1;
std::string::iterator it;
for ( it = res1.begin() ; it < res1.end(); it++)
{ std::cout << "checking " << *it << ' ';
if (!( '0' <= *it && *it <= '9' )) {
std::cout << "this is a numeral\n";
} else {
std::cout << "you entered: " << *it << " -- this is *not* a numeral\n";
}
}
I want to create a while loop that will allow me to input a mix of string numbers until I input string that contains all characters.
Also, I have a problem with output
int main() {
string name;
string temp;
cout << "Enter your name:";
cin >> name;
cout << endl;
for(auto a:name) {
if(isalpha(a)) {
temp=name;
} else {
while(!isalpha(a)) {
cout << "Enter your name without digit:";
cin >> name;
cout << endl;
}
}
}
cout << temp << endl;
}
for(auto a:name) {
This is a loop over the characters in name, as entered after the prompt "Enter your name:". The current character is assigned to a.
if(isalpha(a)) {
temp=name;
}
If the letter is alphabetic, assign temp = name (every time the current letter is alphabetic... this is not what you want!).
else {
...if the current character (a) is not alphabetic...
while(!isalpha(a)) {
...enter a second loop, which will loop until a is alphabetic...
cout << "Enter your name without digit:";
cin >> name;
cout << endl;
}
...but a is never again assigned to. Your loop does not terminate.
You should re-work your logic. As this looks like a self-study project, I will not write the reworked loop for you, as I think you will learn much more from trying to do it on your own.
When advancing the state of an object, use of std::swap works well for simple objects and pointer swaps. For other in place actions, Boost.ScopeExit works rather well, but it's not terribly elegant if you want to share exit handlers across functions. Is there a C++11 native way to accomplish something similar to Boost.ScopeExit but allow for better code reuse?
(Ab)use std::unique_ptr's custom Deleters as a ScopeExitVisitor or Post Condition. Scroll down to ~7th line of main() to see how this is actually used at the call site. The following example allows for either std::function or lambdas for Deleter/ScopeExitVisitor's that don't require any parameters, and a nested class if you do need to pass a parameter to the Deleter/ScopeExitVisitor.
#include <iostream>
#include <memory>
class A {
public:
using Type = A;
using Ptr = Type*;
using ScopeExitVisitorFunc = std::function<void(Ptr)>;
using ScopeExitVisitor = std::unique_ptr<Type, ScopeExitVisitorFunc>;
// Deleters that can change A's private members. Note: Even though these
// are used as std::unique_ptr<> Deleters, these Deleters don't delete
// since they are merely visitors and the unique_ptr calling this Deleter
// doesn't actually own the object (hence the label ScopeExitVisitor).
static void ScopeExitVisitorVar1(Ptr aPtr) {
std::cout << "Mutating " << aPtr << ".var1. Before: " << aPtr->var1;
++aPtr->var1;
std::cout << ", after: " << aPtr->var1 << "\n";
}
// ScopeExitVisitor accessing var2_, a private member.
static void ScopeExitVisitorVar2(Ptr aPtr) {
std::cout << "Mutating " << aPtr << ".var2. Before: " << aPtr->var2_;
++aPtr->var2_;
std::cout << ", after: " << aPtr->var2_ << "\n";
}
int var1 = 10;
int var2() const { return var2_; }
// Forward declare a class used as a closure to forward Deleter parameters
class ScopeExitVisitorParamVar2;
private:
int var2_ = 20;
};
// Define ScopeExitVisitor closure. Note: closures nested inside of class A
// still have access to private variables contained inside of A.
class A::ScopeExitVisitorParamVar2 {
public:
ScopeExitVisitorParamVar2(int incr) : incr_{incr} {}
void operator()(Ptr aPtr) {
std::cout << "Mutating " << aPtr << ".var2 by " << incr_ << ". Before: " << aPtr->var2_;
aPtr->var2_ += incr_;
std::cout << ", after: " << aPtr->var2_ << "\n";
}
private:
int incr_ = 0;
};
// Can also use lambdas, but in this case, you can't access private
// variables.
//
static auto changeStateVar1Handler = [](A::Ptr aPtr) {
std::cout << "Mutating " << aPtr << ".var1 " << aPtr->var1 << " before\n";
aPtr->var1 += 2;
};
int main() {
A a;
std::cout << "a: " << &a << "\n";
std::cout << "a.var1: " << a.var1 << "\n";
std::cout << "a.var2: " << a.var2() << "\n";
{ // Limit scope of the unique_ptr handlers. The stack is unwound in
// reverse order (i.e. Deleter var2 is executed before var1's Deleter).
A::ScopeExitVisitor scopeExitVisitorVar1(nullptr, A::ScopeExitVisitorVar1);
A::ScopeExitVisitor scopeExitVisitorVar1Lambda(&a, changeStateVar1Handler);
A::ScopeExitVisitor scopeExitVisitorVar2(&a, A::ScopeExitVisitorVar2);
A::ScopeExitVisitor scopeExitVisitorVar2Param(nullptr, A::ScopeExitVisitorParamVar2(5));
// Based on the control of a function and required set of ScopeExitVisitors that
// need to fire use release() or reset() to control which visitors are used.
// Imagine unwinding a failed but complex API call.
scopeExitVisitorVar1.reset(&a);
scopeExitVisitorVar2.release(); // Initialized in ctor. Use release() before reset().
scopeExitVisitorVar2.reset(&a);
scopeExitVisitorVar2Param.reset(&a);
std::cout << "a.var1: " << a.var1 << "\n";
std::cout << "a.var2: " << a.var2() << "\n";
std::cout << "a.var2: " << a.var2() << "\n";
}
std::cout << "a.var1: " << a.var1 << "\n";
std::cout << "a.var2: " << a.var2() << "\n";
}
Which produces:
a: 0x7fff5ebfc280
a.var1: 10
a.var2: 20
a.var1: 10
a.var2: 20
a.var2: 20
Mutating 0x7fff5ebfc280.var2 by 5. Before: 20, after: 25
Mutating 0x7fff5ebfc280.var2. Before: 25, after: 26
Mutating 0x7fff5ebfc280.var1 10 before
Mutating 0x7fff5ebfc280.var1. Before: 12, after: 13
a.var1: 13
a.var2: 26
On the plus side, this trick is nice because:
Code used in the Deleters can access private variables
Deleter code is able to be centralized
Using lambdas is still possible, though they can only access pubic members.
Parameters can be passed to the Deleter via nested classes acting as closures
Not all std::unique_ptr instances need to have an object assigned to them (e.g. it's perfectly acceptable to leave unneeded Deleters set to nullptr)
Changing behavior at runtime is simply a matter of calling reset() or release()
Based on the way you build your stack it's possible at compile time to change the safety guarantees on an object when the scope of the std::unique_ptr(s) go out of scope
Lastly, using Boost.ScopeExit you can forward calls to a helper function or use a conditional similar to what the Boost.ScopeExit docs suggest with bool commit = ...;. Something similar to:
#include <iostream>
#include <boost/scope_exit.hpp>
int main() {
bool commitVar1 = false;
bool commitVar2 = false;
BOOST_SCOPE_EXIT_ALL(&) {
if (commitVar1)
std::cout << "Committing var1\n"
if (commitVar2)
std::cout << "Committing var2\n"
};
commitVar1 = true;
}
and there's nothing wrong with that, but like was asked in the original question, how do you share code without proxying the call someplace else? Use std::unique_ptr's Deleters as ScopeExitVisitors.
Imagine you have a stack of unique_ptr to something (an int to simplify), like:
std::stack< std::unique_ptr<int> > numbers;
numbers.push( std::unique_ptr<int>( new int(42)) );
But if you try to use the top element, without getting it from the stack, you will get an compile error:
if( not numbers.empty() ){
auto lastone = numbers.top();
std::cout << "last " << *lastone << std::endl;
}
You should move out the element, use it, and then put again in the stack:
if( not numbers.empty() ){
auto lastone = std::move(numbers.top());
numbers.pop();
std::cout << "last " << *lastone << std::endl;
numbers.push( std::move(lastone) );
}
Is there a better way to do this?
If you don't intend to actually pop the element but just want to use it inplace, just use a reference:
auto& lastone = numbers.top();
std::cout << "last " << *lastone << std::endl;
I am creating a large pintool and I have two questions:
The tool (abridged below to the relevant part only) sometimes cannot identify the image/routine for particular executed instructions. Does anybody know when/why can that happen?
The tool (when instrumenting a Barnes-Hut benchmark) always terminates with an out-of-memory (OOM) error after running for a while (although the benchmark, when run standalone, completes successfully). Which tools to use to debug/trace the OOM error of Pin-instrumented applications?
int main(int argc, char *argv[])
{
PIN_InitSymbols();
if( PIN_Init(argc, argv) )
{
return 0;
}
INS_AddInstrumentFunction(Instruction, 0);
PIN_StartProgram();
return 0;
}
VOID Instruction(INS ins, VOID *v)
{
INS_InsertPredicatedCall( ins,
IPOINT_BEFORE,
(AFUNPTR) handle_ins_execution,
IARG_INST_PTR,
.....);
}
VOID handle_ins_execution (ADDRINT addr, ...)
{
PIN_LockClient();
IMG img = IMG_FindByAddress(addr);
RTN rtn = RTN_FindByAddress(addr);
PIN_UnlockClient();
if( IMG_Valid(img) ) {
std::cerr << "From Image : " << IMG_Name( img ) << std::endl;
} else {
std::cerr << "From Image : " << "(UKNOWN)" << std::endl;
}
if( RTN_Valid(rtn) ) {
std::cerr << "From Routine : " << RTN_Name(rtn) << std::endl;
} else {
std::cerr << "From Routine : " << "(UKNOWN)" << std::endl;
}
}
I recently asked this on the PinHeads forum, and I'm awaiting a response. What I have read in the documentation is that the IMG_FindByAddress function operates by looking "for each image, check if the address is within the mapped memory region of one of its segments." It may be possible that instructions are executed that are not within the valid ranges.
The best way to know what image it is in for cases like this is to look at the context. My pintool (based on DebugTrace) continues to run even without knowing what image it is in. You can look at the log entries before and after this occurs. I see this all the time in dydl on OSX.