1

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.

CrushCode
  • 13
  • 4
  • 1
    `std::cin >> i`, `std::getline(std::cin)`, etc. Check out what `istream`s can do: http://en.cppreference.com/w/cpp/io/basic_istream – myaut Jan 07 '17 at 09:16
  • modifying the property pages isn't an ideal way of doing it – pcodex Jan 07 '17 at 10:21

3 Answers3

0

You want to redirect cin to a file and for that you need to set the stream buffer associated with cin using

ios::rdbuf()

Take a look here

and a couple more on SO here and here

Community
  • 1
  • 1
pcodex
  • 1,812
  • 15
  • 16
-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
  • Thanks a lot. I never know that before. – lampv Jan 07 '17 at 09:41
-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