#include <iostream>
// #include <conio>
using namespace std;
int main(){
int choice;
double temp, result;
std::cout <<"Enter temprature";
std::cin>>temp;
std::cout<<"Enter number between 1 or 2";
std::cin>>choice;
switch (choice){
case 1 :
result = (5*temp /9) - 32;
std::cout<<"answer is" <<result<<"C \n";
break;
case 2 :
result = (9/5*temp) + 32;
std::cout <<"answer" <<result<<"F";
break;
default : std::cout<<"Wrong number";
}
return 0;
}
I'm using this code for basic conversion (switch practice) and there comes Timeout error. I'm new to cpp so please don't mind if you find this easy.
Also, How can i use conio.h functions like getch() in this program?
I'm facing this error :
Enter temprature
Timeout - Some common reasons for Timeout
Your Program may have a endless loop
Ah, Finally found the error. It seems that you are using JDoodle, and didn't provide any input to stdin! This is quite simple to solve. Simply click the box that says Stdin Inputs..., and write on the first line the input for the first prompt, and on the second the input for the second prompt. Here is a sample screenshot:
The only problem with this is that every single output is on the same line, so you may want to add a few newlines in your code.
As a second solution, you could turn interactive mode on (The button right above the stdin inputs), which would actually ask you for the input while running the program. This solution may suit your needs better, since it makes more sense.
As far as conio.h goes, You will be unable to use functions from that header (Which is good, since they are nonstandard), unless you are working locally on a Windows computer.
Your code compiles in MSVS 2015, and seems to work.
This:
result = (5*temp /9) - 32;
is not the right formula. It should be
result = 5 * (temp - 32) / 9;
This:
result = (9/5*temp) + 32;
suffers from integer overflow. It should be:
result = (9.0 / 5 * temp) + 32;
or
result = (9 * temp / 5) + 32;
How can i use conio.h functions like getch() in this program?
conio.h is not a standard header and getch() is not a standard function, so although you may be able to use them on some platforms they will not be available on others.
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.
What is causing my code to behave unexpectedly?
The program is freezing (not crashing) before it reaches expected part of the code. The program is fully contained inside main(), and isolating the whole code the expected statement makes it work correctly. Why is it happening?
I was coding a yet poor solution for this codeforces problem, that I was intending to refine little by little. The problem is that curiously my program freezes when reading the input (like if it was an infinite loop, it doesn't crash). I tried both C++ and C++11 on GCC, and both of them froze. Tried Ideone, and the same happened. It could be anything, except that I copied everything from the first include to the output line that would confirm that all the input was read and ran only this excerpt.
#include <bits/stdc++.h>
using namespace std;
typedef unsigned uint;
int main() {
ios_base::sync_with_stdio(false);
uint n, h, k, buf;
vector<uint> potatoes;
cin >> n >> h >> k;
for (uint i = 0; i < n; ++i)
{
cin >> buf;
potatoes.push_back(buf);
}
cout << "Letf\n";
return 0;
}
This is a reduced version that contains all the lines that are part of the logic of the input stage. The expected input is
5 6 3
5 4 3 2 1
Here are the links for the full code and the correctly working excerpt.
The main problem is your while (true) {...}. Your "algorithm" makes this loop infinitely.
And if you don't know, there is an Tutorial and source code for the round already
http://codeforces.com/blog/entry/45181
Finally, please look carefully at the problem page. The Contest Materials part have useful things for you.
In case the title is not precisely revealing what I want to do, the following is my problem.
I want to write a c++ program in a Linux or Mac terminal to print numbers that keeps counting from 1, 2, 3 ... at the same position under a command line mode. For example, it is like displaying the number of percentage when your work is progressing(e.g. downloading something, installing software...).
I wrote a simple for-loop to print numbers and use usleep(1000); for a delay of 1 second before printing next number. Then I use cout << "\b"; trying to move cursor back to display coming number at the same position. However I fail to create the effect that I want, the numbers are printed in a line.
I am not a skillful c++ programmer and know very limited on programming in a terminal environment. Can anyone help to give me hint or sample code for this function? Thanks!!
If you are in Linux Terminal you can also use the following code,
system("clear");
cout<<"\b";
cout<<Your_Number;
// Repeat this in a loop and call the delay function
This works in terminal for me (am using linux)
#include
#include
using namespace std;
int main(int argc, char *argv[]) {
int i;
for(i=1;i<100;i++)
{
cout<<"\b\b\b"<<i;
cout.flush();
sleep(1);
}
return 0;
}
I'm an absolute beginner to programming and i'm just doing some exercises exercises for the beginning.
First of all, i'm using Visual C++ 2010 to compile C-Code. I just create a new project and choose an empty console application. After that, I create a ressource file named test.c and change in the file properties the elementype to C/C++ Compiler and compile as C++ Code, so that i can use #include <iostream> for the std::cin.get() command. Now the code:
#include <stdio.h>
#include <iostream>
int main()
{
int number1, number2;
int sum;
puts("Enter number 1 please:");
scanf_s("%d",&number1);
puts("Enter number 2 please:");
scanf_s("%d",&number2);
std::cin.get();
std::cin.get(); //(1)
sum = number1 + number2;
printf("The average is %f\n", sum/2);
return 0;
}
Now my problem ist that the "std::cin.get()" command is just ignored. Afer typing in the two numbers the program just stops and the console window closes.
Any idea where the problem is?
I have another question please.
Since my problem with holding the console open is solved (1), now my printf() gives me just zeros as output. I want to have a float number as output but no matter what i type in as number1 and number2 i always get "0.000000".
Since i'm still working on my little program to verify the input before it is accepted, i have another question please.
I want to use the following code just to check the input.
#include <stdio.h>
#include <iostream>
#include <ctype.h>
int main()
{
int number1, number2;
int sum;
puts("Enter number 1 please:");
scanf_s("%d",&number1);
if (isdigit(number1))
{
puts("Enter number 2 please:");
scanf_s("%d",&number2);
}
else
{
puts("Your input is not correct. Enter a number please.");
}
std::cin.get();
std::cin.get();
/*
sum = number1 + number2;
printf("The average is %f\n", sum/2); */
return 0;
}
Well it doensn't work. I type in a digit and my response is "Your input is not...". I have used the search and found the following: Check if User Inputs a Letter or Number in C. Unfortunately the suggestions doesn't help me.
It's not ignored. When you type your second number, then hit enter, it puts your number plus a newline character in the input stream. scanf removes the number, but leaves the newline character alone. When you call cin.get(), since there's a character in the stream, it doesn't wait for your input.
PigBen has already given you a good explanation of where you err. However, I have some additonla points to make about your program which won't fit into a comment:
You are mixing C and C++ input. Why? What's wrong with std::cin >> number1?
When you change number1 to double, you need to remember to change the formatting string in scanf(), too, while with IO streams the compiler will figure out everything for you. With streams and C++' strings, containers and other data structures, it's much harder to do something that compiles, but invokes the dreaded Undefined Behavior at run-time.
Also note that you do not check whether your inputting operations succeed. What happens if I invoke your program, and instead of passing it numbers, I enter non-digits? Never use input from users, files, or other externals sources unverified.
With IO streams, the input operator >> returns (a reference to) the stream, and you can use streams as if they were booleans, so you can do
if(std::cin >> number1)
// input succeeded
or
if( !(std::cin >> number2) ) // note the negation operator !
// input error
to check.
Streams enter a bad state internally after input/output errors. Any further IO operations will fail on a stream that had encountered an error. Therefore, if you want, you can delay input verification until all input operations are done:
std::cout << "Enter number 1 please:";
std::cin >> number1;
std::cout << "Enter number 2 please:";
std::cin >> number2;
if(!std::cin)
// input error
However, remember to always verify input before you first use it.
Note that I didn't check the output for errors. That's because it's hard to imagine something going wrong with output to the console. (And what would you do about it? Print an error message?) However, if you write into a file, remember to check output, too. It's easy for a file operation to go wrong.
In answer to your modified question it is because you are using ints for division. Change int sum to float sum and everything should be fine.
To answer your modified question: you're using the %f printf() format with an int, and that doesn't work. If you want to print out floating-point, you need to pass a double. You could print out (double)sum / 2 or even sum / 2.0, both of which yield doubles. (No, a float doesn't work the same for a variadic function like printf().) As it is, you're passing what is probably a four-byte type and telling printf() to treat it as an eight-byte type of different format, so it's no wonder you're not getting the expected results.
Alternately, you could switch to C++ iostreams, which save you the problem of matching types and knowing the default promotions. You'd still get an integer from sum/2, and that would drop any one-half, but it would be the right result.
I am trying to manipulate a string in C++. I am working with an Arduino board so I am limited on what I can use. I am also still learning C++ (Sorry for any stupid questions)
Here is what I need to do:
I need to send miles per hour to a 7 segment display. So if I have a number such as 17.812345, I need to display 17.8 to the 7 segment display. What seems to be most efficient way is to first multiply by 10 (This is to shift the decimal point right one place), then cast 178.12345 to an int (to chop decimal points off). The part I am stuck on is how to break apart 178. In Python I could slice the string, but I can't find anything on how to do this in C++ (or at least, I can't find the right terms to search for)
There are four 7 segment displays and a 7 segment display controller. It will measure up to tenths of a mile per hour. Thank you very much for an assistance and information you can provide me.
It would probably be easiest to not convert it to a string, but just use arithmetic to separate the digits, i.e.
float speed = 17.812345;
int display_speed = speed * 10 + 0.5; // round to nearest 0.1 == 178
int digits[4];
digits[3] = display_speed % 10; // == 8
digits[2] = (display_speed / 10) % 10; // == 7
digits[1] = (display_speed / 100) % 10; // == 1
digits[0] = (display_speed / 1000) % 10; // == 0
and, as pointed out in the comments, if you need the ASCII value for each digit:
char ascii_digits[4];
ascii_digits[0] = digits[0] + '0';
ascii_digits[1] = digits[1] + '0';
ascii_digits[2] = digits[2] + '0';
ascii_digits[3] = digits[3] + '0';
This a way you can do it in C++ without modulus math (either way seems fine to me):
#include "math.h"
#include <stdio.h>
#include <iostream.h>
int main( ) {
float value = 3.1415;
char buf[16];
value = floor( value * 10.0f ) / 10.0f;
sprintf( buf, "%0.1f", value );
std::cout << "Value: " << value << std::endl;
return 0;
}
If you actually want to be processing this stuff as strings, I would recommend looking into stringstream. It can be used much the same as any other stream, such as cin and cout, except instead of sending all output to the console you get an actual string out of the deal.
This will work with standard C++. Don't know much about Arduino, but some quick googling suggests it won't support stringstreams.
A quick example:
#include <sstream> // include this for stringstreams
#include <iostream>
#include <string>
using namespace std; // stringstream, like almost everything, is in std
string stringifyFloat(float f) {
stringstream ss;
ss.precision(1); // set decimal precision to one digit.
ss << fixed; // use fixed rather than scientific notation.
ss << f; // read in the value of f
return ss.str(); // return the string associated with the stream.
}
int main() {
cout << stringifyFloat(17.812345) << endl; // 17.8
return 0;
}
You can use a function such as this toString and work your way up from there, like you would in Python, or just use modulo 10,100,1000,etc to get it as numbers. I think manipulating it as a string might be easier for you, but its up to you.
You could also use boost::lexical_cast, but it will probably be hard to get boost working in an embedded system like yours.
A good idea would be to implement a stream for the display. That way the C++ stream syntax could be used and the rest of the application would remain generic. Although this may be overkill for an embedded system.
If you still want to use std::string you may want to use a reverse iterator. This way you can start at the right most digit (in the string) and work towards the left, one character at a time.
If you have access to the run-time library code, you could set up a C language I/O for the display. This is easier to implement than a C++ stream. You could then use fprint, fputs to write to the display. I implemented a debug port in this method, and it was easier for the rest of the developers to use.