Plus: I redirected standard input by editing the command argumennts in property pages in VS2013. I'm doing a small project and it requires I read a file without using the ifstream cause it's said: The only libraries you may use for this assignment are iostream, iomanip, and string.
Asked
Active
Viewed 1,830 times
3 Answers
-1
You can use "freopen" functionn. Example:
freopen("input.txt","r",stdin).
That means you read a file "input.txt" and save it's contents to "stdin". Now, you can use "cin".

lampv
- 47
- 4
-
This doesn't answer the question (freopen doesn't _read_ file) and uses C library (while question is explicitly tagged C++) – myaut Jan 07 '17 at 09:20
-
So, how can you read data from file by using std::cin >> i, std::getline(std::cin), without opening file? – lampv Jan 07 '17 at 09:32
-
`./a.out < file.txt` That is what is called file input redirection: http://sc.tamu.edu/help/general/unix/redirection.html – myaut Jan 07 '17 at 09:37
-
-1
When file is redirected to stdin (standard input), you should read from std::cin
(instance of std::istream
) which is wrapper around stdin. std::basic_ifstream
is a subclass of std::basic_istream
, so most reading functions are available in both of them and you should familiar with them. Which means that you can use:
std::getline
to read file line by line:std::string s; while(std::getline(std::cin, s)) { std::cout << s << std::endl; }
operator >>
to read fields delimited by space character:while(std::cin) { std::string s; std::cin >> s; std::cout << s << std::endl; }
Check out full list of its operators and functions here: http://en.cppreference.com/w/cpp/io/basic_istream

myaut
- 11,174
- 2
- 30
- 62
-
Yeah, this is the answer that I want ! Thank u really very much! ! ! – CrushCode Jan 07 '17 at 09:54
-
hardly answers the question. The question is about redirection not reading from istreams – pcodex Jan 07 '17 at 10:19