A function in C++ made being skipped? - c++

I have made a function called pause(). Here is the code for it:
void pause(){
std::cin.sync();
std::cin.ignore();
}
I also use a declaration in front of my code:
void pause();
int main(){
}
It worked at first, but now for some reason it just skips the function when I call it...
std::cout << "Random text. Press any key to carry on...";
pause();
EDIT: Unfortunately, when I try it differently, it goes makes me enter something and then I have to press enter. Is there really not a way to make it so that if you press any key (like the ugly system("pause") it immediately carries on? I'll have to make a new thread for this...

This is why it's important to post the smallest complete code you can come up with that compiles and runs and shows the problem. Chances are, though, that there's some input done before calling this function, and it's leaving something in the input buffer. So pause isn't being skipped, but it returns immediately because of the noise in the input.

Related

C++: ctrl+d terminates program (ubuntu)

(New to C++)
I have this simple code (simplified for the question):
int main()
{
string currInput;
while (getline(cin, currInput))
{
}
cout << "wont be printed" << std::flush;
return 0;
}
I have been debugging for a while and I probably miss something:
When running it and pressing ctrl+d (after some strings or right away), it does not print the string that is after the while loop. It just stop running. I thought it might be something with flushing so I added that too.
What am I missing?
PS: When running in debug, it mentions something about sighup signal.
So, with a lot of help from #manni and #rici, we found the problem.
It turns out to be a known problem in cLion.
see sending EOF to stdin in Clion IDE
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206849765-How-to-enter-EOF-Ctrl-z-in-Run-console-
https://youtrack.jetbrains.com/issue/IDEA-12514
Your error is the while loop. You should not be using a loop here. What happens is it hits this line and attempts to get input. Regardless of whether you type in anything or not, if you hit CTRL+D it will end the getline. But you have it in a while loop....so it'll hop back to the top of the loop and get another line...then another line....then another line. Welcome to your first infinite loop.
while (getline(cin, currInput))
{
}
The simplest thing would be to do just
getline(cin, currInput);
If you're starting out programming this is probably what you want to do anyway.
If you feel gutsy, read this page: http://www.cplusplus.com/reference/string/string/getline/
You'll notice that getline returns the stream you pass in. Which will evaluate to true as far the loop is concerned.

C++ output screen disappears

Why does my C++ output screen disappear immediately? I'm a beginner in cpp. Can anyone help me to find the problem please?
You should either launch your application inside of a terminal, or add a line of code that waits for the input in order for the window to not close. E.g. add in the end of the function main a line:
std::cin.get();
And also add at beginning of the file the include that holds that function.
#include <iostream>
This is hard to answer since there can be many things that can cause your output box to close immediately. First try having a cout statement and then a cin statement. Something like:
cout<<"Hello"<<endl;
cin>>input>>endl;
Also make sure to have the necessary include statement at the top and whatever you want to return at the bottom.
#include<iostream>
return 0;
As you have said that you are beginner in C++, you should keep in mind ,three major things while coding in C++. You've mentioned that your screen disappears , then following things you should try.
1). in C++ conventionally main returns value of type int.And the format of your program should be like...
int main()
{
-------
//body of your program
-------
return 0;
}
If the function returns 0, that means it ran successfully.
2). You have to inlcude #include<iostream> on the top of your program.
3).check whether the IDE you are using is compatibale to your operating system or not.
Hope this will help you.

do-while doesn't quit on first 'q'

So I'm working on a simple little text-based game in D to gain some experience working with the language. Here is a do-while loop that I'm currently struggling with:
do{
writeln("a. Advance 1 year\tc. Advance 10 years\tq. Quit");
writeln("b. Advance 5 years\td. Modify faction");
input = chomp(stdin.readln());
switch(input){
...
default:
break;
}
writeln(input[0]);
}while(input[0] != 'q');
Now the problem I'm running into is that when I hit q and enter the loop doesn't exit. It just keeps going. But then after the first time q is input, another q will terminate the loop. The writeln is in there as a sanity check, and it prints out the characters I type in exactly as typed. I feel like I'm going crazy, but it's probably just a simple type-o or something you guys will spot instantly. Nothing in the switch statement modifies 'input'.
EDIT: Okay some people have been asking to see all of the code. Here it is: http://pastebin.com/A7qM5nGW
When I said nothing in the switch modified input, it was to hide the fact I hadn't written anything in the switch yet. I've been trying to get the quit part to work right before adding the more complicated stuff. Also, here's a sample file for what I run it on: http://pastebin.com/4c2f4Z5N
Okay my friend found it. It has nothing to do with the while loop itself. I briefly forgot that args[0] is the name of the program. So it's actually running through the parent loop once with nothing, then actually quitting, and then running through the appropriate loop. It was fixed by making the parent loop like so...
foreach(filename; args[1..$]){
...
do{
...
while(input[0] != 'q');
}
as opposed to:
foreach(filename; args){
etc...

C++ unexpected hangtime

I am trying to write a function in my program that loads a huge text-file of 216,555 words and put them as strings into a set. This works properly, but as expected, it will hang for a few micro seconds while looping through the file. But there is something funky going on with my loop, and it's not behaving properly. Please take the time to read, I am sure there's a valid reason for this, but I have no idea what to search for.
The code, which is working by the way, is this:
ifstream dictionary;
dictionary.open("Dictionary.txt");
if(dictionary.fail())
{
cout<<"Could not find Dictionary.txt. Exiting."<<endl;
exit(0);
}
int i = 0;
int progress = 216555/50;
cout<<"Loading dictionary..."<<endl;
cout<<"< >"<<endl;
cout<<"<";
for(string line; getline(dictionary, line);)
{
usleep(1); //Explanation below (not the hangtime)
i++;
if(i%progress == 0)
cout<<"=";
words.insert(line);
}
The for-loop gets every string from the file, and inserts them in the map.
This is a console-application, and I want the user to see the progress. It's not much of a delay, but I wanted to do it anyway. If you don't understand the code, I'll try to explain.
When the program starts, it first prints out "Loading Dictionary...", and then a "<" and a ">" separated by 50 spaces. Then on the next line: "<" followed by a "=" for every 433 word it loops through (216555/50). The purpose of this is so the user can see the progress. The wanted output half way through the loop would be like this:
Loading dictionary...
< >
<=========================
My problem is:
The correct output is shown, but not at the expected time. It prints out the full progress bar, but that only after it has hanged and are done with the loop. How is that possible? The correct number of '=' are shown, but they all pop out at the same time, AFTER it hangs for some microseconds. I added the usleep(1) to make the hangtime a bit longer, but the same thing happened. The if-statement clearly works, or the '=' would've never showed at all, but it feels like my program is stacking the cout-calls for after the entire loop.
The weirdest thing of all, is that the last cout<<"<"; before the for-loop starts, is also shown at the same time as the rest of its line; after the loop is finished. Why and how?
You never flush the stream, so the output just goes into a buffer.
Change cout<<"="; to cout<<"="<<std::flush;
You need to flush the output stream.
cout << "=" << std::flush;
The program is "stacking the cout-calls". It's called output buffering, and every major operating system does it.
When in interactive mode (as your program is intended to be used), output is buffered by line; that is, it will be forced to the terminal when a newline is seen. You can also have block-buffered (fixed number of bytes between forced outputs; used when piping output) and unbuffered.
C++ provides the std::flush stream modifier to force an output at any point. It can be used like this:
cout << "=" << std::flush;
This will slow down your program a bit; the point of buffering is for efficiency. As you'll only be doing it about 51 times, though, the slowdown should be negligible.

C++ File outputting strange number, and part of code not running

Yeah. So, I'm trying to make a code for a guessing game. In this game, there's a hard mode. In hard mode, you have 15 guesses, and have to guess between 1 and 500. But my problem is this:
I'm trying to have hard mode save & display your wins/losses, but when it outputs the contents of wins.txt it outputs something like this:
Wins: 0x7fffee26df78
Losses: 0x7fffee26e178
It's really confusing me. Here's the part of the code I have for that:
ifstream losses_var("losses.txt");
ifstream wins_var("wins.txt");
losses_var>> loss;
wins_var>> win;
wins_var.close();
losses_var.close();
Then it gets called with:
cout<<"Wins: "<< wins <<"\nLosses: "<< losses <<"\n"
If you would like to see the full source code, it's here: http://pastebin.com/gPT37uBJ
My second problem:
Hard mode won't display when you win. That's pretty much the whole problem. In my code, the loop for asking users for input uses
while (guess != randNum)
So at the end bracket I have what I want the code to display when a user wins, but it just doesn't run. It just stops. I would like it if someone could help me with this. The line that has the bug is line 97 through 105. Again, source code is here: http://pastebin.com/gPT37uBJ
You've got your variable names confused
cout<<"Wins: "<< wins <<"\nLosses: "<< losses <<"\n";
should be
cout<<"Wins: "<< win <<"\nLosses: "<< loss <<"\n";
It's important to pick good variable names. One reason is so that you don't confuse yourself about what your variables mean (if you confuse yourself think how it's going to be for someone else looking at your code).
Others have already answered the output problem (win vs. wins). The other problem is probably in your logic of while loop nesting. The outer loop (while (guess != randNum)) starts, but its body contains the entire inner loop (while (guesses_left != 0)). This means that the outer condition is not checked again until the inner loop terminates, which means you've run out of guesses. Also note that if you guess correctly, inner loop will never terminate. You probably want something like this:
while (guesses_left > 0) {
// input user's guess
if (guess < randNum) {
// process it
} else if (guess > randNum) {
// process it
} else {
// it's equal, user won
// do what's necessary for a win
return 0;
}
}
// ran out of guesses
// do what's necessary for a loss
return 0;
You are not writing your variables win and loss to cout. From your pasted code, I can see that wins and losses are ofstream objects, which means you are probably seeing addresses there. I would advise you to choose more informative variable names to avoid hard to spot mistakes like this.