using is similar to
import in that you need to declare it in every file you want to use it in. For example, in Java you can use
import java.io.*; in a MsgSend class. Then in a MsgRecv class, you would need to use
import java.io.*; again, right? The same is true in C++. If you have a file test.cpp,
using std::cin; is only valid for test.cpp. In other words, another file such as main.cpp would have no knowledge of that using declaration. It is all about the scope of various items. If you used
using std::cin; inside main(), you would only be able to use cin in main(). If you tried to use cin in another function, you would receive an compile error. You would either need to use
using std::cin; before actually using cin inside the function or you would need to use the fully-qualified name std::cin for every time that you used cin. Example:
Code:
#include <iostream>
// Answer To Life, the Universe and Everything test
bool answerCorrect (int answer) {
if (answer != 42)
return false;
return true;
}
// asks user to decide to try again or not
int tryAgain () {
int answer = 'q';
std::cout << "If you wish to quit, type 'q' and press Enter." << std::endl;
std::cout << "Otherwise, type another character and press Enter. ";
answer = std::cin.get();
if (!std::cin.good())
std::cin.clear();
std::cin.sync();
return answer;
}
int main () {
using std::cin;
using std::cout;
using std::cerr;
using std::endl;
int ans = 0;
do {
cout << "What is the answer to Life, the Universe and Everything? ";
cin >> ans;
if (!cin.good()) { //invalid input such as 'a' instead of a number
cin.clear();
cerr << "Your answer was invalid." << endl << endl;
}
else if (!answerCorrect(ans))
cout << "Sorry, but your answer was incorrect." << endl << endl;
else {
cout << "Correct!" << endl;
break; //exit the loop so the program can end
}
cin.sync(); //discard leftover characters in the input buffer
} while (tryAgain() != 'q');
return 0;
} Simple code, but effective. I apologize for the formatting when the input is invalid or someone wants to play again. However, it was just something quick to illustrate the purpose.
Wherever you put using, whether it is globally (outside of everything) or within a function such as main() or whatever, it is confined to that file and further confined to the block of code it is enclosed by, if it is not global.