How would I make my code run when I press a button? - c++

So I'm fairly new to c++ and coding in general, and I tried making a test code that would run when I press a button.
I tried changing for loop to a while loop, but that doesn't help.
Here's what I came up with:
#include <iostream>
#include <Windows.h>
int main() {
int i{ 0 };
bool condition = false;
if (GetAsyncKeyState(VK_HOME)) {
condition = true;
}
for (; condition;) {
std::cout << i << std::endl;
i++;
if (GetAsyncKeyState(VK_END)) {
condition = false;
}
}
}
I thought that the code would work, but the result is this:
The code runs, but it ends straight away...

Your solution, modified to use proper loops.
#include <iostream>
#include <Windows.h>
int main() {
while (!GetAsyncKeyState(VK_HOME))
;
for (size_t i {0}; !GetAsyncKeyState(VK_END); ++i)
std::cout << i << std::endl;
}

I think I found a fix, I tried using a goto statement, and it now works.
If you have a more efficient way, please post :D
#include <iostream>
#include <Windows.h>
int main() {
int i{ 0 };
bool condition = false;
start:
if (GetAsyncKeyState(VK_HOME)) {
condition = true;
}
else {
goto start;
}
while(condition) {
std::cout << i << std::endl;
i++;
if (GetAsyncKeyState(VK_END)) {
condition = false;
}
}
}

Related

How to break out of a nested loop?

Is there any way to break this without if/else conditionals for each layer?
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 20; i++)
{
while (true)
{
while (true)
{
break; break; break;
}
}
}
cout << "END";
return 0;
}
You can wrap the logic in a function or lambda.
Instead of break; break; break; (which won't work) you can return;.
#include <iostream>
using namespace std;
int main()
{
auto nested_loops = []
{
for (int i = 0; i < 20; i++)
{
while (true)
{
while (true)
{
// Done with all the looping
return;
}
}
}
};
nested_loops();
cout << "END";
return 0;
}
Or (same effect, different style)
#include <iostream>
using namespace std;
int main()
{
[] {
for (int i = 0; i < 20; i++)
{
while (true)
{
while (true)
{
// Done with all the looping
return;
}
}
}
} ();
cout << "END";
return 0;
}
If you want to break individual loop, then you can use break in their respect loop.
Putting too many or single break within a loop, will only break that loop that it is within it.
#include <iostream>
using namespace std;
int main()
{
[] {
for (int i = 0; i < 20; i++)
{
while (true)
{
while (true)
{
break;
}
break;
}
break;
}
} ();
cout << "END";
return 0;
}
In order to break out of a nested loop, you can use the goto statement.
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 20; i++)
{
while (true)
{
while (true)
{
goto break_outer_loop;
}
}
}
break_outer_loop:
cout << "END";
return 0;
}
Note that goto should generally be avoided. However, for breaking out of a nested loop, it is generally considered acceptable.

C++ recursive backtracking

I am trying to do recursive backtracking to find a path from point 0 to point 8. I have defined the paths but its goes 0 1 2 and them stops. Can anyone help?
#include <iostream>
#include <vector>
using namespace std;
vector< vector<int> > roads;
void find_path(int Point = 0) {
cout << Point;
int rds = roads.size();
for(int i = 0; i < rds; i++) {
find_path(roads[Point][i]);
}
}
main() {
roads.resize(8);
//VNESUVANJE PATISTA
roads[0].push_back(1);
roads[0].push_back(3);
roads[1].push_back(2);
roads[3].push_back(4);
roads[3].push_back(6);
roads[4].push_back(5);
roads[4].push_back(7);
roads[7].push_back(8);
find_path();
return 0;
}
I did some changes i think now it works properly.
#include <iostream>
#include <vector>
using namespace std;
vector< vector<int> > roads;
int path_finded = 0; //Added new variable to know if path is finded.
void find_path(int Point = 0) {
if(Point == 8) { //Checks if the point where we are is 8 and if it is stops the whole thing and chages path_finded to 1
path_finded = 1;
return;
}
int rds = roads[Point].size();//changed roads.size to roads[Point].size so it gives the size of the possible roads from the point where we are.
for(int i = 0; i < rds; i++) {
find_path(roads[Point][i]);
}
return;
}
main() {
roads.resize(8);
//VNESUVANJE PATISTA
roads[0].push_back(1);
roads[0].push_back(3);
roads[1].push_back(2);
roads[3].push_back(4);
roads[3].push_back(6);
roads[4].push_back(5);
roads[4].push_back(7);
roads[7].push_back(8);
find_path();
if(path_finded == 1) cout << "RABOTI"; //prints if it works.
return 0;
}

compiling in GPU using thrust (prime numbers)

I have a code written in thrust in C language, but i am not able to compile it since i dont have a GPU. My code is supposed to calculate the first 1000 prime numbers. That's it. But the problem is
1 - i can not compile it since i do not have a GPU.
2 - Since i can not compile it, i can not know if it really calculates prime numbers.
Here is my code:
`struct prime{
_host_ _device_
void operator()(long& x){
bool result = true;
long stop = ceil(sqrt((float)x));
if(x%2!=0){
for(int i = 3;i<stop;i+=2){
if(x%i==0){
result = false;
break;
};
}
}else{
result = false;
}
if(!result)
x = -1;
}
};
void doTest(long gen){
using namespace thrust;
device_vector<long> tNum(gen);
thrust::sequence(tNum.begin(),tNum.end());
}
int main(){
doTest(1000);
return 0;
}`
Could someone help me compile my code and display the result, and if not working correctly, then help me fix it?
If you don't have a GPU, then use thrust::host_vector instead of thrust::device_vector.
I've cleaned up your code, and it's running on the CPU like this:
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/sequence.h>
#include <iostream>
int main()
{
thrust::host_vector<long> tNum(1000);
thrust::sequence(std::begin(tNum), std::end(tNum));
thrust::transform(std::cbegin(tNum), std::cend(tNum), std::begin(tNum), [](long x)
{
bool result = true;
long stop = (long)std::ceil(std::sqrt((float)x));
if (x % 2 != 0) {
for (long i = 3; i < stop; i += 2) {
if (x % i == 0) {
result = false;
break;
};
}
} else {
result = false;
}
if (!result) x = -1;
return x;
});
for (const auto& element : tNum) if (element>0) std::cout << element << ", ";
std::cout << std::endl;
std::cin.ignore();
return 0;
}

How to alphabetically sort strings?

I have been trying to use this c++ program to sort 5 names alphabetically:
#include <iostream>
#include <cstring>
#include <conio.h>
using namespace std;
int main()
{
char names[5][100];
int x,y,z;
char exchange[100];
cout << "Enter five names...\n";
for(x=1;x<=5;x++)
{
cout << x << ". ";
cin >> names[x-1];
}
getch();
for(x=0;x<=5-2;x++)
{
for(y=0;y<=5-2;y++)
{
for(z=0;z<=99;z++)
{
if(int(names[y][z])>int(names[y+1][z]))
{
strcpy(exchange,names[y]);
strcpy(names[y],names[y+1]);
strcpy(names[y+1],exchange);
break;
}
}
}
}
for(x=0;x<=5-1;x++)
cout << names[x];
return 0;
}
If I enter Earl, Don, Chris, Bill, and Andy respectively, I get this:
AndyEarlDonChrisBill
Could someone please tell me whats wrong with my program?
You could use std::set or std::multiset (if you will allow repeated items) of strings, and it will keep the items sorted automatically (you could even change the sorting criteria if you want).
#include <iostream>
#include <set>
#include <algorithm>
void print(const std::string& item)
{
std::cout << item << std::endl;
}
int main()
{
std::set<std::string> sortedItems;
for(int i = 1; i <= 5; ++i)
{
std::string name;
std::cout << i << ". ";
std::cin >> name;
sortedItems.insert(name);
}
std::for_each(sortedItems.begin(), sortedItems.end(), &print);
return 0;
}
input:
Gerardo
Carlos
Kamilo
Angel
Bosco
output:
Angel
Bosco
Carlos
Gerardo
Kamilo
You can use the sort function:
#include <algorithm>
#include <vector>
using namespace std;
...
vector<string> s;
sort(s.begin(),s.end());
You are using too much unnecessary loops. Try this simple and efficient one. You need to just swap when a string is alphabetically latter than other string.
Input
5
Ashadullah
Shawon
Shakib
Aaaakash
Ideone
Output
Aaaakash
Ashadullah
Ideone
Shakib
Shawon
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s[200],x[200],ct,dt;
int i,j,n;
cin>>n;
for(i=0;i<n;i++)
{
cin>>s[i];
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(s[i]>s[j])
{
ct=s[i];
s[i]=s[j];
s[j]=ct;
}
}
}
cout<<"Sorted Name in Dictionary Order"<<endl;
for(i=0;i<n;i++)
{
cout<<s[i]<<endl;
}
return 0;
}
Your code implements a single-pass of bubble sort. Essentially missing the 'repeat until no changes are made to the array' loop around the outside.
The code does not take care when the names are already in order. Add the following
else if(int(names[y][z])<int(names[y+1][z]))
break;
To the if statement.
Putting this here in case someone needs a different solution.
/* sorting example */
#include <iostream>
using namespace std;
bool isSwap( string str1, string str2, int i)
{
if(str1[i] > str2[i])
return true;
if(str1[i] == str2[i])
return isSwap(str1,str2,i+1);
return false;
}
int main()
{
string str[7] = {"you","your","must","mike", "jack", "jesus","god"};
int strlen = 7;
string temp;
int i = 0;
int j = 0;
bool changed = false;
while(i < strlen-1)
{
changed = false;
j = i+1;
while(j < strlen)
{
if(isSwap(str[i],str[j],0))
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
changed = true;
}
j++;
}
if(changed)
i = 0;
else
i++;
}
for(i = 0; i < strlen; i++)
cout << str[i] << endl;
return 0;
}

Question about bool in C++

I was wondering why the code below only returns "Test" four times, instead of five?
#include <iostream>
#include <cassert>
using namespace std;
class CountDown
{
public: //Application Programmer Interface
CountDown(int start); // it is set to start
void next(); // subtracts one from it
bool end()const; //
private:
int it;
};
CountDown::CountDown(int start)
{
it = 0;
it = start;
}
void CountDown::next()
{
it = it - 1;
}
bool CountDown::end() const
{
if (it <= 0)
cout << "The countdown is now over" << endl;
}
int main()
{
for( CountDown i = 5 ; ! i.end(); i.next())
std::cerr << "test\n";
}
There is no point in doing this double initialization:
CountDown::CountDown(int start)
{
it = 0;
it = start;
}
This is enough:
CountDown::CountDown(int start)
{
it = start;
}
Or even this, using the initialization list:
CountDown::CountDown(int start):it(start)
{
}
As for end() you don't return any value from it. The method should probably look like this:
bool CountDown::end() const
{
return it <= 0;
}
try this.
bool CountDown::end() const
{
if (it > 1) return false;
return true;
}