#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int num, num2;
num = 33;
do
{
cout <<"\n" <<num-3;
}
while (num >=3);
system("PAUSE");
return EXIT_SUCCESS;
}
I have coded the above but when I run it, it outputs 30 and does not deplete the value to 3.
How can I have the loop do this? I know that num-- would work but that would only deplete the value by one. I'm new to c++ and I am trying to figure these things out.
Thanks! :)
//edit thanks I have it working now with num = num - 3, num-=3 works too
this line:
cout <<"\n" <<num-3;
does not change the value of num. It just outputs the value of num - 3. To actually change the value you need another line, such as:
num -= 3;
Even if you do as suggested and subtract 3 (or whatever) every iteration of your loop, it may not do a whole lot of good. The problem is fairly simple: you're likely updating your variable a lot faster than the output can be printed, so you may easily see a dozen or more values all appear at essentially the same time.
To cure that, you generally want to pause for a short time between iterations, so one value will (probably) be visible before the next is printed. Based on the system("pause");, I'm going to guess you're running Windows, in which case code something like this may be a bit more to your liking:
#include <cstdlib>
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
int num = 33;
do
{
cout <<" \r" << (num-=3);
Sleep(100);
}
while (num >=3);
return EXIT_SUCCESS;
}
Related
I'm trying to solve a problem from the site open.kattis.com https://open.kattis.com/problems/different
the problem is you take in two non-negative integers from 0 to 10^15 and you calculate the difference. I wrote this and it calculates it correctly, but it is not fast enough, how can I make it faster?
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
long long int a, b;
while(a != 0){
cin >> a >> b;
if (a > b) { cout << a-b << endl;}
else{ cout << b-a << endl;}
}
return 0;
}
The real performance hit, if ran many many times would come from the 'endl' actually, because while it adds a '\n' at the end, it also flushes the stream. Any other micro optimization is quite meaningless at best, I'm sure the compiler is smart enough to put a fast enough code in it's place.
EDIT: Could also add std::ios::sync_with_stdio(false); if you are REALLY desperate for potential performance increase. This prevents the synchronization between C style streams. See: sync
Rather than doing a comparison to see which is bigger, which takes more time, you could just forget about which is bigger and calculate the difference anyway: cout << a-b << ends; If b is larger than a then yes you will end up with a negative result. In which case, multiply it by -1. I work mainly in C but I think in C++, it would look something like this: first store the result of the calculation in a variable 'x' long long int x = a-b, then if (x < 0) { x *= -1 ;}. This should work if my code is correct; I'm not sure if it will be much faster but it's definitely worth a try.
EDIT: Or, like #user64322 said, you could do the same as above, but rather than multiplying by -1, just take the absolute value, which is the same, but quicker.
In addition to the others' suggestions, an obvious thing you can do is use argv to take command line arguments at startup (e.g. ./PrintDiffQuick 10 5 would print 5) instead of blocking execution while waiting for user input.
#include <cinttypes>
#include <iostream>
int main(int argc, const char **argv)
{
std::ios::sync_with_stdio(false);
std::cout << std::imaxabs(std::strtoimax(argv[1], nullptr, 10) -
std::strtoimax(argv[2], nullptr, 10)) << '\n';
return 0;
}
I'm quite new to C++(two days actually) and I would like to know if it is possible to do some parallelization with this code. I need this to be a hell lot faster as there are millions of iterations. From what I've understood so far it is not possible to parallelize, as the only for loop I use depends on the iteration before, which doesn't allow parallelization. Right? And if parallelization is not possible, how to optimize it otherwise so it gets faster. I was quite surprised as this only runs 3x faster than my original python code. (some said C++ is up to 100 to 400x faster than python)
If the VisualStudio 2015 project files are needed, please tell me..
If you run the application:
You need to enter a sha1 hash and then tell the programm how many characters the base word had, so for example the word test:
hash: a94a8fe5ccb19ba61c4c0873d391e987982fbbd3
length: 4
Thanks in advice
#include "stdafx.h"
#include <stdio.h>
#include <string>
#include <iostream>
#include <cstring>
#include "..\crytoPP\sha.h"
#include "..\crytoPP\filters.h"
#include "..\crytoPP\hex.h"
#include "..\crytoPP\channels.h"
using namespace CryptoPP;
using namespace std;
int found = 0;
int iteration = 0;
int length;
char source[] = "abcdefghijklmnopqrstuvwxyz";
string solution = " didn't match";
string base_hash;
string CHECK(string hash, int argc, char** argv);
void COMBINATIONS(string b, int length, int source_length, int argc, char** argv);
int main(int argc, char** argv)
{
char *arr_ptr = &source[0];
int source_length = strlen(arr_ptr);
cout << "Please enter hash:";
cin >> base_hash;
cout << "Please enter length:";
cin >> length;
transform(base_hash.begin(), base_hash.end(), base_hash.begin(), ::toupper);
COMBINATIONS("", ::length, source_length, argc - 1, argv + 1);
system("PAUSE");
return 0;
}
string CHECK(string hash, int argc, char** argv) {
if (::found == 0) {
iteration++;
cout << iteration << endl;
if (argc == 2 && argv[1] != NULL)
hash = string(argv[1]);
string s1;
SHA1 sha1; SHA224 sha224; SHA256 sha256; SHA512 sha512;
HashFilter f1(sha1, new HexEncoder(new StringSink(s1)));
ChannelSwitch cs;
cs.AddDefaultRoute(f1);
StringSource ss(hash, true /*pumpAll*/, new Redirector(cs));
cout << s1 << endl;
if (s1 == ::base_hash) {
::found = 1;
cout << " =" << hash << endl;
}
return s1;
}
}
void COMBINATIONS(string b, int length, int source_length, int argc, char** argv) {
if (::found == 0) {
if (length == 0) {
CHECK(b, argc, argv);
}
else {
for (int i = 0; i < source_length; i++) {
COMBINATIONS(b + ::source[i], length -1, source_length, argc -1, argv + 1 );
CHECK(b, argc - 1, argv + 1);
}
}
}
}
The first thing you should try is to remove your output in every iteration as this does significantly reduce the performance of your program.
Right now you are invoking COMBINATIONS only once with an empty string b, but if you would create one thread for every starting string b of size 1 in main you can have e.g. 26 threads each solving an equally sized part of the problem. Yet, best would be to try to rewrite the COMBINATIONS function to be better suited for parallelism.
Moreover you are currently leaking memory every time you call CHECK which right now might not seem as much as a problem, however the longer the word you are looking for, the more memory your program will require. C++ requires you to manage the memory yourself, so you should at least free all the memory you allocated with new by using delete (to make sure it can be reused). Even better if you would try to reuse those objects you created as memory allocations are somewhat slow as well.
Last but not least please rethink the purpose of incrementing/decrementing argc and argv. Frankly I do not quite understand your intention there and it seems evil.
This is supposed to take the input and move each letter 1 to the right. Is the pause stopping it from doing anything?
How can I change it so that it doesn't just output what the user inputs?
This is the code in C++ in Visual Studio Community 2013:
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <string>
#include <cctype>
int _tmain(int argc, _TCHAR* argv[])
{
string cyphertext;
cout << "Paste your cyphertext and press enter to shift right 1: ";
cin >> cyphertext;
void encrypt(char * cyphertext, unsigned int offset);
for (int i = 0; cyphertext[i] != 0; i++) {
char firstLetter = islower(cyphertext[i]) ? 'a' : 'A';
unsigned int alphaOffset = cyphertext[i] - firstLetter;
int offset = 0;
unsigned int newAlphaOffset = alphaOffset + offset;
cyphertext[i] = firstLetter + newAlphaOffset % 26;
cout << "" << "Right One: " << cyphertext;
system("pause");
return 0;
}
}
Your pause is inside the 'encrypting' loop. It needs to be outside. The return in the loop will terminate the program; that too needs to be outside the loop.
Note that it is easier to see such mistakes when the code is indented in an orthodox layout such as the one now in the question. Working with scratty layouts makes it really hard to see many problems that are obvious when the code is tidily laid out.
You also declare a function encrypt() which you never use; don't do that. And it's generally a bad idea to declare functions inside other functions. And given that there isn't an encrypt() function defined, there isn't a 'void function', so I've changed the question title for you.
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've got a homework assignment in my C++ programming class to write a function that outputs the binary value of a variable's value.
So for example, if I set a value of "a" to a char I should get the binary value of "a" output.
My C++ professor isn't the greatest in the whole world and I'm having trouble getting my code to work using the cryptic examples he gave us. Right now, my code just outputs a binary value of 11111111 no matter what I set it too (unless its NULL then I get 00000000).
Here is my code:
#include <iostream>
#define useavalue 1
using namespace std;
void GiveMeTehBinary(char bin);
int main(){
#ifdef useavalue
char b = 'a';
#else
char b = '\0';
#endif
GiveMeTehBinary(b);
system("pause");
return 0;
}
void GiveMeTehBinary(char bin){
long s;
for (int i = 0; i < 8; i++){
s = bin >> i;
cout << s%2;
}
cout << endl << endl;
}
Thanks a ton in advance guys. You're always extremely helpful :)
Edit: Fixed now - thanks a bunch :D The problem was that I was not storing the value from the bit shift. I've updated the code to its working state above.
The compiler should warn you about certain statements in your code that have no effect1. Consider
bin >> i;
This does nothing, since you don’t store the result of this operation anywhere.
Also, why did you declare tehbinary as an array? All you ever use is one element (the current one). It would be enough to store just the current bit.
Some other things:
NULL must only be used with pointer values. Your usage works but it’s not the intended usage. What you really want is a null character, i.e. '\0'.
Please use real, descriptive names. I vividly remember myself using variables called tehdataz etc. but this really makes the code hard to read and once the initial funny wears off it’s annoying both for you when you try to read your code, and for whoever is grading your code.
Formatting the code properly helps understanding a lot: make the indentation logical and consistent.
1 If you’re using g++, always pass the compiler flags -Wall -Wextra to get useful diagnostics about your code.
Try this:
#include <bitset>
#include <iostream>
int main()
{
std::bitset<8> x('a');
std::cout << x << std::endl;
}
it's actually really simple. to convert from decimal to binary you will need to include #include <bitset> in your program. inside here, it gives you a function that allows you to convert from decimal to binary form. and the function looks like this:
std::cout << std::bitset<8>(0b01000101) << std::endl;
the number 8 in the first argument means the length of the output string. the second argument is the value you want to convert. by the way, you can input a variable in binary form by declaring a 0b in front of the number to write it in binary form. note that to write in binary form is a feature added in c++14 so using any version lower than that won't work. here is the full code if you want to test it out.
#include <iostream>
#include <bitset>
int main()
{
std::cout << std::bitset<8>(0b01000101) << std::endl;
}
note that you don't have to input a binary number to do this.
#include <iostream>
#include <bitset>
int main()
{
std::cout << std::bitset<8>(34) << std::endl;
}
output:
00100010
Why not just check each bit in the unsigned char variable?
unsigned char b=0x80|0x20|0x01; //some test data
int bitbreakout[8];
if(b&0x80) bitbreakout[7]=1;
//repeat above for 0x40, 0x20, etc.
cout << bitbreakout;
There are a TON of ways to optimize this, but this should give you an idea of what do to.
#include <iostream>
using namespace std;
int main(){
int x = 255;
for(int i = numeric_limits<int>::digits; i >=0; i--){
cout << ((x & (1 << i)) >> i);
}
}
it's actually really simple. if you know how to convert decimal to binary, then you can code it easily in c++. in fact I have gone ahead and created a header file that allows you not only to convert from decimal to binary, it can convert from decimal to any number system. here's the code.
#pragma once
#include <string>
char valToChar(const uint32_t val)
{
if (val <= 9)
return 48 + val;
if (val <= 35)
return 65 + val - 10;
return 63;
}
std::string baseConverter(uint32_t num, const uint32_t &base)
{
std::string result;
while (num != 0)
{
result = valToChar(num % base) + result;
num /= base;
}
return result;
}
now, here is how you can use it.
int main()
{
std::cout << baseConverter(2021, 2) << "\n";
}
output:
11111100101