Reputation: 49
I get this strange error. I think I have included all necessary files. What could cause this? The error is caused by this line :
cin >> x >> "\n" >> y >> "\n";
Here is the code:
#ifndef ARITMETICE_H
#define ARITMETICE_H
#include <iostream>
#include <string>
#include "UI\comanda.h"
using namespace Calculator::Calcule;
namespace Calculator{
namespace UI{
template<int Operatie(int, int)>
class CmdAritmetice : public ComandaCalcule
{
public:
CmdAritmetice(const string &nume) : ComandaCalcule(nume)
{
}
void Execute()
{
cout << Nume() << "\n";
cout << "Introduceti doua numere intregi (x, y)\n";
int x, y;
cin >> x >> "\n" >> y >> "\n"; // here a get the error
cout << x << " " << Nume() << " " << y << " = " << Operatie (x,y) <<"\n";
}
};
}
}
#endif
Upvotes: 0
Views: 1602
Reputation:
If your intention is to consume white spaces and one new line character (note the are flavors of new line representations), you might write a manipulator
#include <cctype>
#include <iostream>
#include <sstream>
std::istream& nl(std::istream& is) {
typedef std::istream::traits_type traits;
while(true) {
traits::int_type ch;
if(std::isspace(ch = is.get())) {
if(ch == '\n') break;
}
else {
is.putback(ch);
// No space and no '\n'
is.setstate(std::ios_base::failbit);
break;
}
}
return is;
}
int main()
{
std::istringstream s("1\n2");
int x, y;
s >> x >> nl >> y >> nl;
std::cout << x << ' ' << y << '\n';
if(s.fail()) {
// The missing '\n' after '2'
std::cout <<"Failure\n";
}
return 0;
}
Upvotes: 0
Reputation: 18411
cin
is object of type istream
. This class has overloaded operator >>
to take input from console and put the value into given variable. The variable must be l-value, not r-value. In short, the expression given on right of >>
must be writable variable.
This will not work:
const int x;
cin >> x;
Simply because x
is a const int&
, and not int&
which what istream::operator>>(int&)
expects.
Going this way further, when you make a call:
cin >> "\n";
You are essentially calling operator >> (const char*)
and not operator >> (char*)
, and hence the error. Because of multiple overloads of operator>>
and template code behind, the error is not clear.
Note: The exact signature of operator >>
might differ, but problem is with const-ness.
Upvotes: 0
Reputation: 1135
cin >> must has a writable variable in the right, your cin>>"\n" redirect cin to a const char* type, which is read only
in a word, just use cin>> x >> y; and the iostream will do the rest for you.
Upvotes: 0
Reputation: 385088
Not sure what you expected to happen when you tried to extract data from a stream into a string literal!
Upvotes: 1
Reputation: 52461
The problem is cin >> "\n"
. It purports to read user input into a string literal, which doesn't make any sense. Just drop it, make it cin >> x >> y;
Upvotes: 3