I have a problem with do while loop which is escaped when user hit some key. I increase some value by 1 every time it loops. But when I'm printing this value (after every key press) the value is getting printed two times.
The code is as below:
#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;
int main () {
int x = 0;
char asd;
do {
x++;
asd = getch();
cout << x << " ";
} while(asd!=27);
system("pause");
return 0;
}
I need to check if the key has been pressed, but I dont know how to fix this issue with double printing every time key has been pressed.
Some help?
This is because getch() reads not only the character you do input, but also the new line feed.
You do actually write some_character and \n into the input stream. Both are characters and both are read.
You need to ignore rest of the stream, after the 1st character read.
Another thing it might be is that some keys generate two character codes "0 or 0xE0, and the second call returns the actual key code".
You can see what is really happening with something like this:
#include <iostream>
#include <windows.h>
#include <conio.h>
using namespace std;
int main () {
int x = 0;
char asd;
do {
x++;
asd = getch();
cout << "Character code read: " << int(asd)
<< ", character count:" << x << "\n";
} while(asd!=27);
}
This will print actual key codes of what is read, so you will see what is going on.
Related
I have been looking for a way to pause the console display. I found some suggestions out on the internet but it's not working the way I'd like it to.
My Question: How can I improve this pause() function to recognize any key (including the enter key)?
I'll tell you what happened first and then show you the snippet of code.
I found some helpful way to pause the screen I wrote a small pause() function and called it in my mainline
The function puts out a line "Press any key to continue..."
I ran the program and the line was put to the screen but did not pause
Thinking that something was in the input buffer and it was being pulled off I added a line to display the hex value of the 1st character of the line.
What displayed was not in hex (bummers) but it did show that my output display line split. So I think it is an end-of-line character (I removed that line to display in hex because it was not working as I wanted it to)
I have updated the function and it now displays the hex character and the character is x'0a' (Line Feed)
So I added a line to pull that end-of-line character before issuing the cin.get() to pause the screen
That worked. Console was paused
I hit the ENTER key and the input was taken but the program did not resume
I then hit the 'x' letter key and the program resumed
BUT .. the logic in pause() was supposed to throw an error. It did not. The test for 'x' did not work.
The value after I hit the 'x' key is actually a line feed (x'0a')
Here is the code:
#ifndef MYFUNCTIONS
#define MYFUNCTIONS
#include <cstdio>
#include <cstdlib>
using std::cout;
using std::cin;
void pause() {
string holdit;
//std::cout.flush();
//std::cin.clear();
std::cout << std::endl << "Press any key to continue...";
std::cin >> holdit;
holdit = std::cin.get();
std::cout << "The first character in holdit is <" << holdit[0] << "> x'" << setfill('0') << setw(2) << std::hex << (int)holdit[0] << "'" << endl;
if (holdit[0] == 'x') throw 99;
}
#endif
Thanks, in advance, for your help.
After quite a few attempts at creating a pause() function, I have it. It recognizes the ENTER key as well as any other key. The function includes a cout statement to display the 1st character in hex (which I used during my debugging). If you have any comments, please let me know. I'm a beginner at C++. So be kind :) Thanks.
#ifndef MYFUNCTIONS
#define MYFUNCTIONS
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;
void pause()
{
char holdit;
cout << "Press any key to continue..." << endl;
holdit = _getch();
cout << "holdit = < x'" << setfill('0') << setw(2) << hex << (int)holdit << "'>" << dec << endl;
if (holdit == 'x') throw 99;
}
#endif
#include "stdafx.h"
#include "iostream"
#include "thread"
#include "conio.h"
#include "windows.h"
using namespace std;
void incrm();
void charget();
void main() {
thread count(incrm);
thread getcin(charget);
count.join();
getcin.join();
cin.get();
}
void incrm() {
int j = 0; // used to increment and output
while (true) {
cout << "\r" << j; // outputs 1,2,3,4... and so on
j++;
Sleep(150);
}
cout << endl;
}
void charget() {
while (true) {
int i = getch(); // gets value of char
cout << "\r\nCHAR: " << i; // and here is the problem...!
}
}
So I wanted this program to output a number in the first line, which increments without stopping and if you hit any key it should cout the value of that key in a secound line, so i wanted it to output something like this->
45
CHAR: 97
and after you have hit a key the incrementing number should stay in the first line. If you hit several keys the second cout should be overwritten, but this doesnt seem to work for me, my output looks like this if i hit several keys->
10
12AR: 97
20AR: 96
My problem is that my first cout (the incrementing number) overwrites my second (or my second my first I don't really know) and then this countinues for every line! :(
I suggest you to use windows function called gotoxy(). You can apply this using
SetConsoleCursorPosition();
this function is availible in windows.h library.
It is possible to read more about it here:
Link
So I'm a beginner programmer... and I can't figure out what the problem is in this bit of code I'm writing for a text adventure. All I want it do At the moment is let the user enter a command, and then it converts it to ALLCAPS and prints that out. It should output this:
What shall I do?
pie
Your raw command was: PIE
But instead, it outputs this:
What shall I do?
pie
PIE
...and then it freezes. Here's the code:
#include <iostream>
#include <string>
#include <cctype>
#include <cstring>
#include <vector>
using namespace std;
void command_case();
string userIn;
string raw_command;
int x = 0;
int main()
{
while(raw_command != "QUIT")
{
cout << "What shall I do?\n";
cin >> userIn;
command_case();
cout << "Your raw command was: " << raw_command << endl;
}
return 0;
}
void command_case()
{
char command[userIn.size()+1];
strcpy(command, userIn.c_str());
while(x < userIn.size()+1)
{
if(islower(command[x]))
{
command[x] = toupper(command[x]);
cout << command[x];
x++;
}
else if(isupper(command[x]))
{
cout << command[x];
x++;
}
}
raw_command = command;
}
I think it may be a problem with the while loop in void command_case(), but I can't figure out exactly what that problem is. I'd appreciate any advice you can give me.
One too much:
while(x < userIn.size()+1)
The problem is with the x variable in the command_case() function.
When x becomes 3 (and "command[x] points to the null character at the end of "pie")
neither islower(command[x]) or isupper(command[x]) are true.
Neither section of the if statement executes, so x stays at 3 forever.
Since "userIn.size()+1" is 4, and x never reaches 4, the loop never exits.
A possible solution is remove the "x++" from both sections of the if statement, and have a single "x++" after the if statement. This will increment x during every loop regardless of what character "command[x]" points to.
You could easily do something like
void command_case()
{
for(int i =0; i<userIn.size(); i++)
{
userIn[i] = toupper(userIn[i]);
}
}
then cout<<userIn in the main
You should remove all cout calls from command_case() function. In fact the whole if-branch in the function is useless and you could just replace it with the following:
command[x]=toupper(command[x]);
For the simplicity you could replace the whole command_case() function with (just remember to #include <algorithm>):
std::transform(userIn.begin(), userIn.end(), userIn.begin(), toupper);
I have a program like this:
#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
for (int i = 0; i < 10; i++)
{
cout << int (_getch ()) << endl;
}
_getch ();
return 0;
}
If I press keys like digits, alphabets and Enter, a single integer is displayed (per iteration of the loop). However, if I press keys like Insert, Delete, or the arrows, two integers are displayed at once.
Why does this behaviour occur?
From _getch()
When reading a function key or an arrow key, each function must be called twice;
The first call returns 0 (for F1-F10) or 0xE0 (224) (for others) , and the second call returns the actual key code.
So I'm trying to force a preceding 0 to an int so it can be processed later on. Now, all the tutorials i've seen on SO, or any other website, all use something similar to this:
cout << setfill('0') << setw(2) << x ;
Whilst this is great, i can only seem to get it to work with cout, however, I don't want to output my text, i just want the number padded, for later use.
So far, this is my code..
#include <iostream>
#include <string>
#include <iomanip>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <sstream>
/*
using std::string;
using std::cout;
using std::setprecision;
using std::fixed;
using std::scientific;
using std::cin;
using std::vector;
*/
using namespace std;
void split(const string &str, vector<string> &splits, size_t length = 1)
{
size_t pos = 0;
splits.clear(); // assure vector is empty
while(pos < str.length()) // while not at the end
{
splits.push_back(str.substr(pos, length)); // append the substring
pos += length; // and goto next block
}
}
int main()
{
int int_hour;
vector<string> vec_hour;
vector<int> vec_temp;
cout << "Enter Hour: ";
cin >> int_hour;
stringstream str_hour;
str_hour << int_hour;
cout << "Hour Digits:" << endl;
split(str_hour.str(), vec_hour, 1);
for(int i = 0; i < vec_hour.size(); i++)
{
int_hour = atoi(vec_hour[i].c_str());
printf( "%02i", int_hour);
cout << "\n";
}
return 0;
}
The idea being to input an int, then cast it to a stringstream to be split into single characters, then back to an integer. However, anything less than the number 10 (<10), I need to be padded with a 0 on the left.
Thanks guys
EDIT:
The code you see above is only a snippet of my main code, this is the bit im trying to make work.
Alot of people are having trouble understanding what i mean. so, here's my idea. Okay, so the entire idea of the project is to take user input (time (hour, minute) day(numeric, month number), etc). Now, i need to break those numbers down into corresponding vectors (vec_minute, vec_hour, etc) and then use the vectors to specify filenames.. so like:
cout << vec_hour[0] << ".png";
cout << vec_hour[1] << ".png";
Now, i know i can use for loops to handle the output of vectors, i just need help breaking down the input into individual characters. Since i ask users to input all numbers as 2 digits, anything under the number 10 (numbers preceding with a 0), wont split into to digits because the program automatically removes its preceding 0 before the number gets passed to the split method (ie. you enter 10, your output will be 10, you enter 0\n9, and your output will be a single digit 9). I cant have this, i need to pad the any number less than 10 with a 0 before it gets passed to the split method, therefore it will return 2 split digits. I cast the integers into stringstreams because thats the best way for splitting data types i found (incase you were wondering).
Hope i explained everything alot better :/
If I understand correctly your question, you can just use those manipulators with a stringstream, for instance:
std::stringstream str_hour;
str_hour << setfill('0') << setw(2) << int_hour;
String streams are output streams, so I/O manipulators affect them the same way they affect the behavior of std::cout.
A complete example:
#include <sstream>
#include <iostream>
#include <iomanip>
int main()
{
std::stringstream ss;
ss << std::setfill('0') << std::setw(2) << 10; // Prints 10
ss << " - ";
ss << std::setfill('0') << std::setw(2) << 5; // Prints 05
std::cout << ss.str();
}
And the corresponding live example.
int and other numeric types store values. Sticking a 0 in front of an integer value does not change the value. It's only when you convert it to a text representation that adding a leading 0 changes what you have, because you've changed the text representation by inserting an additional character.
X-Y Problem, I think
for ( int i = 0; i < POWER_OF_TEN; i++ )
{
vector<int>.push_back(num%10);
num /= 10
}
?
Then reverse the vector if you want
yes i know this is not real code
if you really want characters, vector<char>.push_back(num%10 + '0')?