I am currently using Visual Studio 2013. I've never used the debugger for my C++ code before, but I used to use it all the time for programming my MSP430. Anyways, I'm trying to get back into programming and trying to use the debugger to step through my code and follow the logic of my if/else statements. When I try to use the debugger to do this, once it begins going into all of the prewritten C++ code for terms such as if, #include, ect. I am trying to get my debugger to ignore all of the standard C++ behind the scenes details, and just step through my code. I messed with Microsoft "My Code Only" feature, but can't seem to get it to do what I desire. Worst case, I guess I have to set a breakpoint after after line I want to go through, but was curious if there was an easier method. Thanks!
UPDATE:
Here is the example code I am using to test your suggestions.
#include <iostream>
#include <string>
using namespace std;
int main(){
cout << "line one\n";
cout << "line one\n";
cout << "line one\n";
cout << "line one\n";
cout << "line one\n";
cout << "line one\n";
cout << "line one\n";
cout << "line one\n\n";
string input;
cin >> input;
cout << "line one";
cout << "line one";
cout << "line one";
return 0;
}
It's nothing pretty, but I'm trying to just step from the first cout statement, see it displayed in my console window, click a button, have it display the next cout statement, repeat, well repeatedly.
I'm sure I'm just not implementing the suggestions correctly. When I try the step out method, it ends up running all of my cout statements. Is this just because I'm trying to do a cout operation, instead of a logic tree, such as if/whiles/ ect?
Here's the illogical mess I'm actually trying to use this method to trace my path through the logic. It's pretty bad code, but before I scrap it and rewrite it, I was trying to figure out how to step through it and trace the mess.
#include <iostream>
#include <string>
using namespace std;
int main(){
string action;
bool running = 1;
int turn = 1;
while (running){
//display map
if (turn == 1){
//ask for user input
cout << "Choose a planet (ex: A1 or D4) or END turn: ";
cin >> action;
if (action == "END"){
if (turn == 1){
turn = 2;
}
else {
turn = 1;
}
}
}
else{
cout << "It is not your turn";
turn = 2;
}
//change players turn
}
return 0;
}
I'm trying to step through my nested conditionals, because when I run the code it just prints "It is not your turn" for ever. I'm pretty sure I know the real reason it does this, but debugging this snippets not the purpose of the question. :)
When stepping through the code with MSVC debugger you usually have two options (to be used after setting a breakpoint or having your debugger started and your program paused somehow):
Step into (shortcut F11)
Step out (shortcut F10)
the first enters in detail into function calls, operator overrides, object construction and doesn't leave an instruction until everything has been "stepped through", while the latter is what you want: a "high level" overview that just skips everything in which an instruction can be decomposed and "jumps" to the next instruction.
The "Just my code" used to be a managed-feature only but it seems they've enabled it for native C++ as well. This can be useful to avoid pestering the stack trace with lots of unnecessary entries, but the step-in and step-out mechanism still holds.
Edit: the above works IFF your app is compiled in debug mode. Release mode is an optimized version for.. well.. releasing programs to the end-users. That means it won't have debugging information and thus setting breakpoints won't work as expected.
For the code above:
Make sure you're compiling in debug mode (you can change this by going into the project properties)
Put a breakpoint on the first statement of your main() function
Launch the debugger
When the execution stops on the line you put the breakpoint into, press F10 to step to the next instruction
Notice that the execution will be passed to the program when you step over a console input operation to let you digit something on the terminal screen. It will resume in the debugger as soon as you enter the newline character.
In addition to just "stepping out" immediately after stepping into an operator or new or an accessor that is not of interest, there is also a context menu item "Step into ..." that will bring up a dialog asking which function you actually want to step into. When this works (my experience is that it is often a bit flakey), it will allow you to completely bypass other getters, operators, etc., that are used before the function call of interest is called.
Sometimes, however, the simplest thing is to set a breakpoint in the function that you want to step into and then Continue. I find this the best approach if I'm needing to do it repeatedly.
Related
I have a very simple program that won't give any console output.
I've tried getting input at the end using cin.get() and holding with system("pause"). I've also tried getting input at the start of the program then outputting at the end.
#include <iostream>
using namespace std;
int main(){
int bulb, bulbOpen=0, multiple;
for ( bulb=1; bulb<101 ; bulb=bulb+1 ){
for ( multiple=1; 100; multiple++){
if (bulb/multiple==0){
bulb = bulb * (-1);
}
}
if ( bulb<<0 ){
bulbOpen = bulbOpen + 1;
}
}
cout << "The remaining open light bulbs are " << bulbOpen << "." << endl;
return 0;
}
I'm a beginner programmer so any help, recommendations and explanations are very welcome.
EDIT:
Thanks to Rapha for the fixes and the advice, here's the updated code:
#include <iostream>
int main(){
int bulb, bulbCopy, bulbOpen=0, multiple;
for ( bulb=1; bulb<101 ; bulb++ ){
bulbCopy = bulb;
for ( multiple=1; multiple<101; multiple++){
if (bulbCopy%multiple==0){
bulbCopy = bulbCopy * (-1);
}
}
if ( bulbCopy<0 ){
bulbOpen = bulbOpen + 1;
}
}
std::cout << "The remaining open light bulbs are " << bulbOpen << "." << std::endl;
std::cin.get();
return 0;
}
The exercise went like this: You've got 100 light bulbs. You take every number from 1-100 and for every lightbulb with the position a multiple of said number, you switch it's current state. So basically if you've got bulb 2, you first switch it ON because it's a multiple of 1, then you switch it OFF because it's a multiple of 2.
And you've got to check how many remaining lightbulbs are still open by the end.
The answer is 10.
The Main-Problem why you get no output is, that the code is causing an infinity-loop (The loop cant escape and will run forever) and you never reach the std::cout part of the code
Ok there's a lot going on and the first thing is (You probably will hear this a lot on this platform) don't use using namespace std; instead use the std::-prefix for c++-Standard Things. I think its ok to use if you start out, but its a really bad Practice.
Then another thing is, cin.get() already 'pauses' or interrupting the program until you entered an input so system("pause") really isn't needed here.
To get input simply do it like that:
int input;
std::cin >> input;
std::cout << "My output was: " << input;
Then another thing is, i dont really know what you try to do with the nested for-loops but in the second for-loop you have a conditions that doesnt really make sense
for(multiple=1; 100; multiple++)
^^^
What you probably want is something like
for(multiple=1; multiple<100; multiple++)
And then saying bulb/multiple==0 doesn't really make sense either, because its only true if bulb is 0, maybe you mean bulb%multiple==0 (modulo).
And there's probably a typo in one condition where you wrote bulb<<0 where you probably want to write bulb<0
But no matter what you do, it still runs into a infinite loop, because the conditions are weird. And in normal cases you really shouldn't change the iteration-variable of your loop inside your loop (only if you know thats exactly what you want) but in most cases that just breaks your program, especially if youre starting to learn the language.
Maybe if you say exactly what you want, we can help you more.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm working on a school project (I'm in seventh grade) and it's about why I want to be a computer programmer. I have to make a presentation of sorts about what a computer programmer is and what they do. I thought it would be a good idea to code my own presentation in a way. I've coded some of it already but i'm stuck. This is what I have so far,
#include <iostream>
#include <string>
using namespace std;
int main()
{
string question;
cout << "Type [1] to begin...";
cin >> question;
if(question == "1")
{
cout << "A computer programmer figures out the process of
designing, writing, testing, debugging, and maintaining the source c
ode for computer programs";
return 0;
}
}
Now what i want to be able to do is add a "goto" type of statement where it can go to something like "int second()" and cout something new like "what are programming languages?" and then a description of what they are after the user inputs something like "yes". Any help would be appreciated. I'm really new to c++. Thanks :)
I think this question is more suited for codereview, but since the code does not compile as is, we may as well help you with your broken code (and then you take it to codereview)
First, let's format your code. This is a useful skill to learn because it helps other coders help you write better code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string question;
cout << "Type [1] to begin...";
cin >> question;
if(question == "1") {
cout << "A computer programmer figures out the process of
designing, writing, testing, debugging, and maintaining the source c
ode for computer programs";
return 0;
}
}
Easiest way to format is to copy it into an IDE, use the IDE to format, then copy it back here, select the code and press the button.
Now to solve this problem.
Your question seems centred around controlling the flow of the program - being able to transition from one stage to the next in a way that puts the user in control and only delegates control back to your program once the user has made a decision.
The problem
Ask the user to enter a 1
Display the following text
A computer programmer figures out the process of designing, writing,
testing, debugging, and maintaining the source code for computer
programs
Ask the user if they wanted to continue
If so, display the following:
what are programming languages?
4b. If not, end the program.
Ask the user if they wanted to continue
etc, etc
As you can see, there is indeed a pattern and this pattern comes down to the following:
Ask what the user wants to do
Do it
Repeat until you run out of slides or the user doesn't want to continue
And just like that, we have abstracted away the complexity and are only focused on following the pattern.
Pay attention to the repeat part because that is what allows this pattern to work for more than one slide of your presentation. There are many ways to represent the repeat part, and for that you should find some good tutorials to teach you some of them. I won't bother describing all of them (just search youtube, you will find tons), but for this particular problem, the best way to represent your pattern is with a do-while loop.
Here is what it will look like:
do {
// Ask the user a question
// Get the user's input
// validate the user's input
// if they want to see the slide show it
// other wise, leave this loop
while (I have not run out of slides);
This is psuedo-code, but here is how it transforms your code:
#include <iostream>// cin, cout
#include <string> // string
#include <vector> // vector
#include <cstddef> // size_t
using namespace std;
int main() {
vector<string> slides = {
"A computer programmer figures out the process of"
"designing, writing, testing, debugging, and maintaining the source c"
"ode for computer programs",
"what are programming languages?",
// Add more here
};
size_t current_slide_index = 0;
string user_response;
do {
cout << "Type [1] to continue: ";
cin >> user_response;
cin.ignore(100, '\n'); // This is used to skip to the next line
if (user_response == "1") {
cout << slides.at(current_slide_index) << std::endl;
} else {
break;
}
} while (++current_slide_index < slides.size());
cout << "Happy learning\n";
return 0;
}
A few notes
I used a vector to hold the slides. This is the most recommended collection type in C++. There are many others, but for the most part, a vector will serve you well.
cin >> does not normally go to the next line after reading something, so I had to manually shift it to the next line. That's the reason for cin.ignore(100, '\n');
As I said in the beginning, this question is more suited for codereview, so take what I've shown you here, make your changes as you learn more about it, and later on have it reviewed once again by the folks at https://codereview.stackexchange.com/.
I think you can try a pattern like this:
#include <iostream>
#include <string>
using namespace std;
void q1()
{
cout << "A computer programmer figures out the process of "
"designing, writing, testing, debugging, and maintaining the source "
"code for computer programs.\n";
}
void q2()
{
cout << "what are programming languages? ...\n";
}
// void q3() ... ... ...
int main()
{
string question = "1";
cout << "Type [1] to begin... ([99] for quiting): ";
cin >> question;
/* while loop: http://en.cppreference.com/w/cpp/language/while */
while (question != "99") {
/* if statement: http://en.cppreference.com/w/cpp/language/if */
if (question == "1") {
q1(); // this is a "function call", you are invoking q1()
}
else if (question == "2") {
q2();
}
// else if(... q3() ... q4() ... and so on.
/* read a new response for checking in the while condition */
cout << "Next? ";
cin >> question;
}
return 0;
}
Using the the goto can be accomplished as below. You can also use the SWITCH..CASE to accomplish the same.
int main()
{
string question;
label:
cout << "Type [1,2,....] to begin...";
cin >> question;
if(question == "1")
{
cout << "A computer programmer figures out the process of designing, writing, testing, debugging, and maintaining the source code for computer programs" << endl;
goto label;
}
if(question == "2")
{
cout << " A programming language is a type of written language that tells computers what to do in order to work" << endl;
}
First of all it's fantastic that you want to be a programmer and I wish you luck on your assignment. You can certainly ask about learning c++ here, but this site is focused on question and answer, not on teaching. You have a pretty specific question here, but it can be solved in a broad variety of ways, which I'm sure you'll learn about soon.
What I would recommend for a presentation is to ignore the input so you don't have as many branches in your code. Then you can simply add the next part directly after the first.
string question;
cout << "Type [1] to begin...";
cin >> question;
cout << "A computer programmer figures out the process of
designing, writing, testing, debugging, and maintaining the source c
ode for computer programs";
cout << "Type [1] to continue...";
cin >> question;
cout << "Part 2";
return 0;
On the language choice:
C++ is definitely the wrong language to start. Because it's the most complicated programming language in existence(it's not an opinion, it's Science). You can't fully understand C++ without understanding other subset languages it contains. For example, C.
Don't listen to people that say you can code without complete understanding. You'll waste your time and won't become real engineer.
C is most stable and continuously respected programming language in Human History. Most modern CS celebrities like Mark Zucker., etc, started with C.
C can look as impressive as C++, if that's what you're interested in.
On the problem:
What you're doing is console dialog with finite determined input. In CS it's called "finite automata" or "state machine". State machine can be represented as a bunch of circles(states) and arrows between them: "Do this if the next input is that". Pick a starting circle and the end circle. i.e. your program terminates when it gets there. Such diagram are really that simple.
Step-by-step solution(fill in blanks):
0)Define IO.
Your input: 1 integer:
int input;
Your output: const strings of characters.
1) Draw state machine diagram, with states and arrows between them. Denote each arrow as Integer, output_string.
For example, '1, "A computer programmer figures.."' - is an arrow from the starting state (0) to some other state (1).
2) Create integer for states:
int state = 0;
3) Translate your state machine into diagram as following:(You don't need goto's. Loop can play as a goto)
while(scanf("%d", &input)){
switch(state){
case 0:
switch(input){
case 1:
printf("A programmer blabla\n");
state = 2;
break;
case 2:
...
{
break;
case 1:
...
case 10: // - last state
switch(input){
...
default:
printf("goodbye");
return 0; // terminate the program;
}
}
}
You need to know about while loops, Switch statements, printf() and scanf(). Wikipedia is ok.
After you did this put the code inside main function and make necessary includes and you're good to go. You need to complete your homework yourself.
when I try to debug this code to read from a file and display it, the console screen comes and goes quickly and I don't understand why it's doing this. Can anyone help me please?
#include "Questions.h"
#include <iostream>
using namespace std;
const int MAXITEMS = 10;
struct quiz
{
string question;
string anser;
};
int main ()
{
string str;
ifstream ifs("Questions2.txt.txt");
getline (ifs,str);
cout << "first line of the file is " << str << ".\n";
return 1;
}
You should click some breakpoints in VS window.Then when you press F5,it will pause at breakpoint, then it will run continue until you press F5 again.
Or,if you make sure your code is correct.You can press Ctrl+F5.This means "Run Without Debug".
This situation,your program will run to end and suggest you "Press any key to continue".
Sorry for my bad english. Hope you can understand.
try with ifs.open, and then assure yourself by using ifs.is_open () function with an if and an error code, I always use it and it worth
and of course, use a breakpoint before the return (clicking it or using system ("pause")
You can try including a pause function. This way it will display your data and then wait for a response. I've included the function I typically use.
void myPause()
{
cout << " Press enter to continue... ";
char blank[8];
cin.getline(blank,8);
cin.sync();
}
Unless you run with some breakpoints, Visual Studio will close the window after the program terminates.
If you want the window to stay on the screen, use Debug->Start without debugging
Or, add a breakpoint at return 1;
Press F10 instead of F5. By pressing F10, you can go line by line
Suppose we have a menu which presents the user with some options:
Welcome:
1) Do something
2) Do something else
3) Do something cool
4) Quit
The user can press 1 - 4 and then the enter key. The program performs this operation and then presents the menu back to the user. An invalid option should just display the menu again.
I have the following main() method:
int main()
{
while (true)
switch (menu())
{
case 1:
doSomething();
break;
case 2:
doSomethingElse();
break;
case 3:
doSomethingCool();
break;
case 4:
return 0;
default:
continue;
}
}
and the follwing menu():
int menu()
{
cout << "Welcome:" << endl
<< "1: Do something" << endl
<< "2: Do something else" << endl
<< "3: Do something cool" << endl
<< "4: Quit" << endl;
int result = 0;
scanf("%d", &result);
return result;
}
Entering numerical types works great. Entering 1 - 4 causes the program to perform the desired action, and afterwards the menu is displayed again. Entering a number outside this range such as -1 or 12 will display the menu again as expected.
However, entering something like 'q' will simply cause the menu to display over and over again infinitely, without even stopping to get the user input.
I don't understand how this could possibly be happening. Clearly, menu() is being called as the menu is displayed over and over again, however scanf() is part of menu(), so I don't understand how the program gets into this error state where the user is not prompted for their input.
I originally had cin >> result which did exactly the same thing.
Edit: There appears to be a related question, however the original source code has disappeared from pastebin and one of the answers links to an article which apparently once explained why this is happening, but is now a dead link. Maybe someone can reply with why this is happening rather than linking? :)
Edit: Using this example, here is how I solved the problem:
int getNumericalInput()
{
string input = "";
int result;
while (true)
{
getline(cin, input);
stringstream sStr(input);
if (sStr >> result)
return result;
cout << "Invalid Input. Try again: ";
}
}
and I simply replaced
int result = 0;
scanf("%d", &result);
with
int result = getNumericalInput();
When you try to convert the non-numeric input to a number, it fails and (the important part) leaves that data in the input buffer, so the next time you try to read an int, it's still there waiting, and fails again -- and again, and again, forever.
There are two basic ways to avoid this. The one I prefer is to read a string of data, then convert from that to a number and take the appropriate action. Typically you'll use std::getline to read all the data up to the new-line, and then attempt to convert it. Since it will read whatever data is waiting, you'll never get junk "stuck" in the input.
The alternative is (especially if a conversion fails) to use std::ignore to read data from the input up to (typically) the next new-line.
1) Say this to yourself 1000 times, or until you fall asleep:
I will never ever ever use I/O functions without checking the return value.
2) Repeat the above 50 times.
3) Re-read your code: Are you checking the result of scanf? What happens when scanf cannot convert the input into the desired format? How would you go about learning such information if you didn't know it? (Four letters come to mind.)
I would also question why you'd use scanf rather than the more appropriate iostreams operation, but that would suffer from exactly the same problem.
You need to verify if the read succeeded. Hint: it did not. Always test after reading that you successfully read the input:
if (std::cin >> result) { ... }
if (scanf("%d", result) == 1) { ... }
In C++ the failed state is sticky and stays around until it gets clear()ed. As long as the stream is in failed state it won't do anything useful. In either case, you want to ignore() the bad character or fgetc() it. Note, that failure may be due to having reached the end of the stream in which case eof() is set or EOF is returned for iostream or stdio, respectively.
I just started learning C++ and I wrote this sample program from the text and when I compile and run it, it just closes after the user inputs any number and presses enter. I'm guessing the answer to this is very obvious so forgive me as newbie here....it's really my first C++ program :P
#include <iostream>
using namespace std;
int main ()
{
int numberOfLanguages;
cout << "Hello Reader.\n"
<< "Welcome to C++.\n"
cout << "How many programming languages have you used? ";
cin >> numberOfLanguages;
if(numberOfLanguages < 1)
cout << "Read the preface. You may prefer.\n"
<< "a more elementary book by the same author.\n";
else
cout << "Enjoy the book.\n";
return 0;
}
Imagine you were designing a model for application execution. You have two choices:
A) When the end of a program is reached it shall terminate.
B) When the end of a program is reached the program shall remain alive in some strange limbo state. It will still retain system resources and will not actually be doing anything, but in order to close the user must terminate it explicitly.
I think anyone would go for option A here, and that is what you are seeing. The end of main is reached and your program exits.
If you would like it to pause at the end take some input from the user, i.e.,
char c;
std::cin >> c;
return 0;
The program closes because there's nothing more for the program to do. It outputs the final statements really really fast and then reaches return 0 which causes it to exit. You'll want to do something there to pause the program.
On Windows, a basic way to do that is system("pause"); (you will need #include <stdlib.h>)
cin.getline is a more standard way to do it.
It closes because the execution reaches return 0; and there is nothing left to do.
If you want the program to wait before closing you could add an something like this:
cout << "Press enter to exit...";
cin >> someVarThatWontBeUsed;
You could also run the program from the command line instead of running the .exe. It will reach end of execution anyway but the prompt will stay open.
Your program ends right after you print out your text. If you want to see anything on the screen you can add a cin right before your return 0 so your program waits for a user response before exiting.
// Wait for user to hit enter
cin >> dummyVar;
return 0;
Either put another read from cin to wait for the user, or open the Command Prompt yourself and run it there.
The program you posted has an error. I was not able to compile what you posted.
cout << "Hello Reader.\n"
<< "Welcome to C++.\n"
is not terminated with a semicolon. I added a semicolon and it compiles and runs as you expect.
Edit: Of course, you have to run the program in a terminal that stays open after the program exits, or use cin to wait for more input, or something like that.
After the user inputs a number, which is saved to numberOfLanguages, it reaches return 0 which returns from the main function and thus the program ends.