简体   繁体   中英

c++ text file redirection getline infinite loop

So I'm having an issue where I am reading in a text file using cin. Here is a basic idea of my code:

while(getline(cin,line) {
cout << line << endl;
}
//Do some task
return 0;

The problem I'm running into is that the loop will not terminate and //Do some task will never run. The only solution that I've found is to look directly at the text file, see how many lines of text there are, and hard code a conditional to break out of it. So say I have a text file with 5 lines and an variable int row. Then I would do something like this:

  while(getline(cin,line) {
cout << line << endl;
if(row == 5) {
break;
}
//Do some task
return 0;

I tried googling but I can't seem to find an answer anywhere. Any ideas? And also only libraries I'm allowed to use is iostream.

#include <iostream>
#include <string>
#include <fstream>

int main()
{
    std::string line;
    std::fstream fin;
    fin.open("test.txt");
    while (getline (fin, line))
        std::cout << line << std::endl;
    fin.close();

    //Do smth here

    return 0;
}

You can use rdbuf to redirect your cin output Following Link will help you. http://www.cplusplus.com/reference/ios/ios/rdbuf/

The following code block should solve your issue: Credit goes to the author: kevinchkin http://www.cplusplus.com/forum/beginner/8388/

#include<iostream>
#include<fstream>

using namespace std;

int main() {

 ifstream myReadFile;
 myReadFile.open("text.txt");
 char output[100];
 if (myReadFile.is_open()) {
 while (!myReadFile.eof()) {


    myReadFile >> output;
    cout<<output;


   }
}
myReadFile.close();
return 0;
}

This is a basic template for reading from a .txt file. I also can not think of any reason why you should not be able to use more than just iostream. They make the other libraries because iostream isn't the best way to go about it. Most(if not all) Teachers/Professors I have had like it when students go above and beyond what the class is studying, and try to learn more. If you need additional help, take a look at: http://www.cplusplus.com/doc/tutorial/files/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM