953,744 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

c++ write single char with cin

hey this is a just for fun topic (a.k.a. NOT homework) but if you can please reply:
I am working in Visual C++ and I can't get any operation to write a single character to a variable and then check it in an if() statement. Here is my last try:

#include <iostream>
using namespace std;

int main()
{
   char k;
   cin>>k;
   if(k='r')
      cout<<k;
   else if(k='f')
      cout<<k<<"!";
   else{}
   cin>>k;
   return 0;
}

Even when I input a 'f', it prints 'r'. It's almost like it's skipping the if().

ben25x
Light Poster
41 posts since Dec 2010
Reputation Points: 10
Solved Threads: 1
 

Your if statements are both using the assignment operator "=" instead of the equality operator "==". The first one will always set k to 'r' and then print it.

tom.wood
Newbie Poster
1 post since May 2010
Reputation Points: 10
Solved Threads: 0
 

oh duh i knew that thanx!

ben25x
Light Poster
41 posts since Dec 2010
Reputation Points: 10
Solved Threads: 1
 

next time, please ask C++ questions in the C++-forum

Nick Evan
Not a Llama
Moderator
10,111 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: