Honestly am shocked I am getting an error. I'm a junior CS major and I can't get this simple program to work. Clion says these two lines are unreachable, yet my test cases seem to work.
Code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "";
while(s != "|") {
int val1 = 0;
int val2 = 0;
cin >> val1;
cin >> val2;
if(val1 == val2) {
cout << "the numbers are equal.\n";
} else {
cout << "the smaller value is: " << min(val1, val2) << '\n'; // Says these two
cout << "the larger value is: " << max(val1, val2) << '\n'; // lines are unreachable
}
cin >> s;
}
return 0;
}
Test Cases:
3 3
the numbers are equal.
f
4 5
the smaller value is: 4
the larger value is: 5
|
Process finished with exit code 0
If this code is so unreachable than how come my program reached it?
There may be a few problems wrong with CLion
This is the one which caught my attention:
You check whether the string is equal to a chat array this may get resolved at runtime but the code checker doesn’t like it. Try using :
char s;
while(s!='|') {...}
Other than that I have no idea...
It may not have predicted the change to the variables, try using the volatile keyword? This may help... That is still a bug.
Related
I'm currently learning c++. I got stuck in this little problem with the exception.
A program asks users to enter 5 integers in an array. I need the program to manage an exception that requests the input of an element again if it already exists.
Here is my code, I figured out the global structure, but the problem is if you enter 0 the program will throw out an exception "already exists", that's not the result I wanted. I know where this comes from, T[j] was not defined in for loop, but I don't know how to deal with it. Could anyone help me to improve it, please? other solutions are also welcomed.
#include<iostream>
#include <vector>
#include<cstdlib>
using namespace std;
int main(){
int i=0,j=0;
int temp;
vector<int>T(5);
do{
try{
cout<<"user input "<<(i+1)<<":";
cin>>temp;
//T[j]= 'a000000000000000000'; //I tried to define T[j], that's maximum I can do
for(j=0;j<=i;j++){
if(T[i]==T[j])
throw(0);
}
T[i]=temp;
i++;
}
catch(const int){
cout<<"Error: value already exists, try again"<<endl;
}
} while(i<sizeof(T)/sizeof(int));
for(i=0;i<sizeof(T)/sizeof(int);i++){
cout<<T[i]<<endl;
}
return 0;
}
This line creates a vector which contains 5 ints. All ints in the vector are zero:
vector<int>T(5);
This line runs a loop. Since i is zero, it runs the loop one time, where j is equal to zero, because j<=i is true, because both of them are zero.
for(j=0;j<=i;j++){
This line checks whether T[i] equals T[j], which it does, because i and j are both zero, and T[0] equals T[0].
if(T[i]==T[j])
This line throws an exception.
throw(0);
Did you spot the bug yet? Maybe you don't want to run the loop where j is equal to i. Maybe you want to loop while j<i instead of j<=i. So if i is 5, j goes from 0 to 4 instead of 0 to 5, and if i is 0, the loop does not run at all.
Also, as Mark Ransom pointed out, this is wrong:
sizeof(T)/sizeof(int)
It should be
T.size()
sizeof(T)/sizeof(int) would work for an array, but not for a vector. You want T.size() instead.
If there isn't a requirement for the numbers to be output in the same order as they were input, a std::set (or std::unordered_set) would work well
#include <iostream>
#include <set>
int main()
{
constexpr int NUMBERS_TO_READ{5};
std::set<int> numbers;
int i = 0;
do
{
int temp;
std::cout << "user input " << (i+1) << std::endl;
std::cin >> temp;
if (numbers.find(temp) != numbers.end())
{
//temp is already in the set
std::cout << "Value " << temp << " already exists, try again!" << std::endl;
}
else
{
//temp isn't in the set. add it.
numbers.insert(temp);
i++;
}
}
while (i < NUMBERS_TO_READ);
for (const auto num : numbers) std::cout << num << std::endl;
}
I'm working my way thought Bjarne Stroustrup Programming Principles and Practice (4.64 Drill #6) and for some reason I can't get "if" to be true.
I've initialized my variables to -1000.
I can't initialize to null.
I've tried just declaring them
I've tried changing the order of my variables.
The problems I've found on stack overflow my code is much different than theirs.
I've currently added a vector which I wasn't using prior.
double val1 = 0; // initialized
double smaller; // initialized
double larger = 0; // initialized
vector<double> compare; // empty vector of doubles
int main ()
{
cout << "Please input a value, us | to stop\n"; // put into
while (cin >> val1) // cin "get from"
{
compare.push_back(val1);
if (val1 < smaller)
{
smaller = val1; // assignment giving a variable a new value
cout << val1 << " is the smallest so far \n" ;
compare.push_back(smaller);
}
else if (val1 > larger)
{
larger = val1; // assignment giving a variable a new value
cout << val1 << " is the largest so far \n";
compare.push_back(larger);
}
else
{
cout << val1 << " error\n";
}
}
}
I can't get smaller "is the smallest so far to print.
I'm teaching myself so any input would be greatly appreciated if anything in my code isn't correct or the best practices please let me know.
Thank You in Advance,
The first value enter must be both the larger and the smaller whatever that value, for that you need to initialize smaller with INFINITY (all valid values are smaller) and larger with -INFINITY (all valid values are larger) and to remove the else to have the two clauses effective for the first value, the third clause has no sense and must be removed.
Is it also useless to use global variables, I encourage you to not use global variables the more you can.
Because the same value can be enter several time perhaps you want a set rather than a vector to not save several times the same value ? However you do not use compare after ...
You write the message Please input... only one time, in that case it is more consistent to say Please input values... or replace
cout << "Please input a value, us | to stop\n"; // put into
while (cin >> val1) // cin "get from"
{
by
while (cout << "Please input a value, invalid value or EOF to stop" << endl,
cin >> val) // cin "get from"
Your code can be changed to be :
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main ()
{
double val;
double smaller = INFINITY; // initialized
double larger = -INFINITY; // initialized
vector<double> compare; // empty vector of doubles
cout << "Please input values, give an invalid value or EOF to stop" << endl; // put into
while (cin >> val) // cin "get from"
{
compare.push_back(val);
if (val < smaller)
{
smaller = val; // assignment giving a variable a new value
cout << val << " is the smallest so far" << endl;
compare.push_back(smaller);
}
if (val > larger)
{
larger = val; // assignment giving a variable a new value
cout << val << " is the largest so far" << endl;
compare.push_back(larger);
}
}
// do something with compare ?
return 0;
}
Execution :
pi#raspberrypi:/tmp $ ./a.out
Please input values, give an invalid value or EOF to stop
1234
1234 is the smallest so far
1234 is the largest so far
1
1 is the smallest so far
222
222222
222222 is the largest so far
-123
-123 is the smallest so far
23
45
aze
pi#raspberrypi:/tmp $
Initialise your variables to INFINITY.
double smaller = INFINITY;
double larger = -INFINITY;
The first value will be smaller/larger than any of those, so you don't limit their value range.
edit: As somebody in the comments pointed out, you would also have to remove the else between the smaller/larger parts, as for that first round, both would apply. As for the third case, not sure what that is meant to do.
Made a while-loop and I'm not getting the result I think I should be getting.
I've done a little debugging and got nothing. Visual Studio 2019 is saying I'm good to go.
int main()
{
double num_enter;
vector<double> nums(0);
while (cin >> num_enter)
{
nums.push_back(num_enter);
sort(nums.begin(), nums.end());
if (num_enter < nums.front())
{
cout << num_enter << " is the smallest one yet.\n" << endl;
}
else if (num_enter > nums.back())
{
cout << num_enter << " is the biggest one yet.\n" << endl;
}
return 0;
}
I want a while(cin>>enter_num) loop to read num_enter and do a vector.push_back(num_enter) followed by the vector sort function and have it out put if the number has been "the smallest yet" or "the biggest yet" but its not working. could you point out what I'm doing wrong? I'm new be gental.
There is only one number in the vector. None of the conditions are met, if you enter one, one is not greater than one or less than one, hence it is not printing anything because you are not handling that case. Add an else block that prints if the numbers are equal then hopefully it will be clear to you why that is happening.
try this
// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
double num_enter;
vector<double> nums(0);
while (cin >> num_enter) {
nums.push_back(num_enter);
//sort(nums.begin(), nums.end());
// Lets say you entered 1
// 1 < 1 -> false
if (num_enter < nums.front())
{
cout << num_enter << " is the smallest one yet.\n" << endl;
}
// 1 > 1 -> false
else if (num_enter > nums.back())
{
cout << num_enter << " is the biggest one yet.\n" << endl;
}
else // 1 == 1
{
cout << "Numbers are equal" << endl;
}
return 0;
}
}
Syntax of vector:
vector vectorName(size);
vector nums(0)
In your code nums is a vector of size zero.
Vector is a dynamic array.
Array of zero size is meaningless.
Check this link to see different ways of declaring vector.
suppose you code order should be changed, the if-elseif-else block should be put in front of the push_back and sort,
or if you really want to maintain the order, if-elseif-else should be corrected like if(num_enter == nums.front()) ... else if(num_enter == nums.back())... else,
only then you can know if your input number has been the biggest or smallest yet.
And initialize like vector<double>nums(0) is little weird, just using vector<double>nums is fine
int i;
cin>>i;
cout<<i
when we entered Character i.e 'A' why it gives Zero output ?
Because A is not a numeric value suitable for storing in an integer, so it will leave your integer alone, as shown here:
#include <iostream>
int main (void) {
int i = 12345;
std::cin >> i;
std::cout << i << std::endl;
return 0;
}
When you run that code and enter A, it outputs 12345 as the value doesn't change.
If you want truly robust input, it's usually better to input lines as strings then convert them yourself.
"Mickey-mouse" programs or those where you have total control over the input can use the sort of input methods you're using, serious code should use more suitable methods.
If your intent is to convert an input character into its integer code, you can use something like:
#include <iostream>
int main (void) {
char c;
std::cin >> c;
std::cout << (int)c << std::endl;
return 0;
}
You should always check if the operation succeeded before continuing.
int i;
if (cin >> i)
cout << i;
else
cout << "Not a valid number!";
because the value 'A' is not stored in the variable i since it is a integer variable. i believe that is the reason the initial value 12345 is printed on the screen...
This question already has answers here:
Infinite loop with cin when typing string while a number is expected
(4 answers)
Closed 3 years ago.
I'm learning C++ and writing little programs as I go along. The following is one such program:
// This program is intended to take any integer and convert to the
// corresponding signed char.
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(true){
std::cin >> n;
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
When I run this program and keep inputs at reasonably small absolute values, it behaves as expected. But when I enter larger inputs, e.g., 10000000000, the program repetitively spits out the same output. Some combinations of input cause erratic behavior. For example:
#: ./int2ch
10
10 -->
10000000000
10 -->
10 -->
10 -->
10 -->
The program spits out "10 --> " until it's killed. (With this particular sequence of inputs, the program's output changes speed erratically.) I also noticed that the output of large values is determined by the previous legal input as well as the value of the current illegal input.
What's going on? (I don't care about fixing the program, that's easy. I want to understand it.)
Basically your cin stream is in a fail state and thus returns immediately when you try to read it. Rewrite your example like this:
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(std::cin >> n){
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
cin >> n will return a reference to cin, which you can test for "good-ness" in a conditional. So basically the the "while(std::cin >> n)" is saying "while i could still read from standard input successfully, do the following"
EDIT: the reason it repeatedly output the last good value entered is because that was the last value successfully read in n, the failed reads won't change the value of n
EDIT: as noted in a comment, you can clear the error state and try again something like this would probably work and just ignore bad numbers:
#include <iostream>
#include <climits>
int main() {
signed char sch = 0;
int n = 0;
while(true) {
if(std::cin >> n) {
sch = n;
std::cout << n << " --> " << sch << std::endl;
} else {
std::cin.clear(); // clear error state
std::cin.ignore(INT_MAX, '\n'); // ignore this line we couldn't read it
}
}
}
Yes, Evan Teran pointed out most things already. One thing i want to add (since i cannot comment his comment yet :)) is that you must put the call to istream::clear before the call to istream::ignore. The reason is that istream::ignore likewise will just refuse to do anything if the stream is still in the fail state.
Given that you are on a 32 bit machine, 10000000000 is too big a number to be represented by an int. Also converting an int to a char will only give you from 0..255 or -128..127 depending on the compiler.
One problem here is that a char has a size of one byte, and thus can only hold a number between -127 and 128. An int on the other hand, is typically 4 bytes, and can take on much larger values. Second problem is that you are inputting a value that is too large even for an int.