I've recently started teaching myself C++, and after having written a lot of user input code, it's made me wonder if there's a simpler way of handling it.
For example, the normal way of doing it would be like this:
#include <iostream>
using namespace std;
int inp;
int guess = 13;
void main(){
cout << "Guess a number: ";
cin >> inp;
if (inp == guess)
cout << endl << "Nice.";
}
But what I want to do is:
#include <iostream>
using namespace std;
int guess = 13;
void main(){
cout << "Guess a number: ";
if (cin == guess)
cout << endl << "Even nicer.";
}
Is there a way to do this? Or this that just improper C++ standard?
In short: No, it's not possible to do as you want it.
You need to understand, that >> is actually a function call of
template<typename T>
std::istream& operator>>(std::istream& is, T& result);
and == is a function call to
template<typename T>
bool operator==(const std::istream&,const T& x);
Where the latter is used to check the stream state, and doesn't extract any user input.
To compare the input the result needs to be extracted from the std::istream in 1st place.
Well you can do it in one line but you don't really need to. But here are some examples anyway
//This will work for a char
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
char test = 'a';
if (getch()== test)
cout<<"\n Works";
return 0;
}
And if you really want
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int x =1;
int y;
for( cin >> y ; x == y ; )
{
cout<<"\n Works";
break;
}
return 0;
}
Or as NathanOliver said you could simply do this
if( cin >> inp && inp == guess )
But really you want to keep it simple as this will confuse others as well as yourself after some time. You want to leave your code as easy as possible
Related
I'm trying to pass input without creating a variable for cin to work with and then having to pass that variable into the parameter of the classes function just so it all can look a little bit cleaner:
#include <iostream>
#include "Customer.cpp"
#include "Customer.h"
using namespace std;
int main()
{
Customer object;
int num;
cout << "Enter a number to be archived: ";
cin >> num;
object.setNum(num); //I don't want to have to do this
num = object.getNum();
cout << num;
}
Two things here:
You can use a constructor for Customer:
int num;
cout << "Enter a number to be archived: ";
cin >> num;
Customer object(num);
num = object.getNum();
cout << num;
If this still doesn't work for you, show a way how you want to code look like so that we could show you how to manage this.
One option would be to implement operator>> and operator<< for Customer, eg:
std::istream& operator>>(std::istream &in, Customer &c)
{
int num;
if (cin >> num)
c.setNum(num);
return in;
}
std::ostream& operator<<(std::ostream &out, const Customer &c)
{
return out << c.getNum();
}
Then you can do this:
#include <iostream>
//#include "Customer.cpp" // <-- DON'T #include .cpp files!
#include "Customer.h"
using namespace std;
int main()
{
Customer object;
cout << "Enter a number to be archived: ";
cin >> object;
cout << object;
}
Hello I've written an algorithm where it prints last number , but I wonder how to make it not to print default value of "number" for example(4.94066e-324) when there's no number written in console/file.
#include <iostream>
using namespace std;
int main() {
double number;
for (; cin >> number;);
cout << number; }
One way is to check wether the first input operation succeeds or not:
#include <iostream>
int main() {
double number;
if(std::cin >> number)
{
while (std::cin >> number);
std::cout << number;
}
else
{
std::cout << "There is no number :(";
}
}
Few things I changed here:
removed using namespace std;, it's considered bad parctice
a while is better suited for this task than a half-empty for
And of course this can be generalized to any std::basic_istream.
You can use a flag to check if you have ever got any input, like this:
#include <iostream>
using namespace std;
int main() {
double number;
bool flag = false;
for (; cin >> number;)
flag = true;
if(flag)
cout << number;
}
using namespace std;
int main()
{
string dna1;
getline(cin, dna1);
string dna2;
getline(cin, dna2);
int hammingDistance=0;
for (int i=0; i < dna1.length(); ++i) {
if (dna1[i] !=dna2[i]) {
hammingDistance++;
}
}
cout <<"HammingDistance is: " << hammingDistance << '\n’;
}
So this is the code I have compiled but it seems to have some error this is from the website Rosalind to which I have added the link below:http://rosalind.info/problems/hamm/
As Michael Roy commented, you're missing the header files you need, iostream and string.
#include <iostream>
#include <string>
You need to format your code though. As it is, it's hard to read, in a regular production-size project, it would be impossible. I also don't recommend using the "using namespace std;" declaration. It's a bad beginner habit to get into.
Everyone has their own specific preferences, but this is roughly what your code should look like.
#include <iostream>
#include <string>
int main()
{
std::string dna1;
std::cin >> dna1;
//getline(cin, dna1);
std::string dna2;
std::cin >> dna2;
//getline(cin, dna2);
int hammingDistance = 0;
for (int i=0; i < dna1.length(); ++i) {
if (dna1[i] != dna2[i]) {
hammingDistance++;
}
}
std::cout <<"HammingDistance is: " << hammingDistance << '\n';
return 0;
}
I used the standard stream methods for input for consistency, but there's nothing technically wrong with other methods, as long as you don't use gets().
I new to programming and was trying to implement struct program in c++, it's simple program but it's not printing proper result. please tell me why?
#include <iostream>
using namespace std;
struct classroom {
int number;
char name[9];
int marks;
void getAndPrint()
{
cout << "struct classroom ";
cin >> number;
cout << number << '\n';
cin.get(name, 9);
//cin>>name;
cout << name;
cin >> marks;
cout << marks;
}
};
int main()
{
classroom room1;
room1.getAndPrint();
int i;
cin >> i;
return 0;
}
In function getAndPrint() I'm using cin.get()..the compiler execute the properly till printing the "number" but when it comes on cin.get(name,9) it print garbage and skips the rest of the code inside the funcion. If i use cin>>name then it's working properly.
Can anyone tell what exactly is the problem?
first, in C++, struct is class with access_modifier is public.
second, you should try read:
Difference between cin and cin.get() for char array
The structure definition does not contain such a function like see
room1.see();
^^^^
I think you mean
room1.getAndPrint();
Also before this statement
cin.get(name, 9);
insert at least this statement
cin.ignore();
Or you even can include the header <limits> and insert statement
#include <limits>
//...
cin.ignore( std::numeric_limits<streamsize>::max(), '\n' );
I'm trying to make a program that flips the words you input. The problem comes when I try to write the word and it asks twice for the input:
cin >> Arr >> myStr;
It is logical that it ask twice but everytime I try to use getline the compiler gives out an error (and even if it worked I have to give the input twice) and I need it to include spaces in the character array.
Here is my full code:
#include <iostream>
#include <string>
using namespace std;
string myStr;
string newVal;
int i;
int main()
{
char Arr[i];
cout << "Enter: ";
cin >> Arr >> myStr;
for (i = myStr.length(); i >= 0; i--)
{
cout << Arr[i];
}
cout << endl;
return 0;
}
The loop works.
The first problem can be corrected by achieving the proper use of getline.
The second one, I have got no idea (use a single input to assign two variables).
Thanks in advance, and I apologise if this is too much of a ridiculous question.
Maybe you can try to have a look to this solution that it's more C++ style than yours:
#include <iostream>
#include <string>
int main() {
std::string myStr;
std::cout << "Please give me a string: ";
if(std::getline(std::cin, myStr)) {
for(std::string::reverse_iterator it = myStr.rbegin();
it != myStr.rend();
++it) {
std::cout << *it;
}
std::cout << std::endl;
}
}
I suggest to you to use always std::string in C++ because has all the methods and function that you could need. So don't waste your time with char array like you do in C.
Here it is, as I said. I was digging around and came up with this:
#include <iostream>
#include <string>
using namespace std;
string myStr;
int i;
int main()
{
cout << "Enter: ";
getline (cin, myStr);
i = myStr.size();
cout << i << endl;
char Arr[i];
for (int a = 0; a <= i; a++)
{
Arr[a] = myStr[a];
}
for (i; i >= 0; i--)
{
cout << Arr[i];
}
return 0;
}
I did not know string contents could also have array-like behaviour. Test it out! Works like a charm (as far as tested).
The way I formatted the code it takes no more than 27 lines of code.
Thanks everyone involved, you helped me a lot.
P.S: Couldn't answer before, I can't do it soon enough with my reputation.