Read newline using stream C++

前端 未结 4 2087
伪装坚强ぢ
伪装坚强ぢ 2021-01-26 18:08

How do I also read a new line using C++ >> operator?

ifstream input(\"doc.txt\".c_str());
vector contents;
while (input >> word) {
    conten         


        
4条回答
  •  悲&欢浪女
    2021-01-26 18:32

    Try using getline (http://www.cplusplus.com/reference/istream/istream/getline/). getline will go through each line (until it sees the new line character) and returns 0 when it reaches end of file. So after each call to getline and printing it print the \n as well. Here is an example for your problem, randFile is a random file with text in it.

      1 #include 
      2 #include 
      3 int main(){
      4 
      5   std::ifstream myFile("randFile", std::ifstream::in);
      6   char s[BUFSIZ];
      7 
      8   while(myFile.getline(s, BUFSIZ)){
      9     std::cout << s << std::endl;
     10     std::cout << "\\n"<< std::endl;
     11   }
     12 
     13   return 0;
     14 }
    

提交回复
热议问题