Wrote the code:

#include <fstream> #include <iostream> using namespace std; int main() { ifstream input ("c:\\f.txt"); string s; getline(input, s); cout << s << endl; system("PAUSE"); return EXIT_SUCCESS; } 

But it displays only the first element from the file. And how to make it so that each time you press the "A" key, +1 element is displayed on the screen?

  • You counted one line and did not do anything with it. Everything works as written. - andrybak
  • And how to make it display the first line of the file? I wrote this: cout << getline (f, line); But he brought only "0". What is the problem? - navi1893
  • getline returns a link to istream , which is converted to a bool , which is converted to an int and 0 is displayed. - andrybak
  • OK, it turned out. I just did not display that. But right now, it shows only the first word, but how to make it so that when you press the "A" key, it displays one by one and the rest? At the expense of pressing a key, I know how to do it. Can you just tell me the code for the file? So that he would draw 2,3, etc. string lines - navi1893

2 answers 2

 std::ifstream input("input.txt"); std::string s; 

Read one line :

 getline(input, s); 

Read one word :

 input >> s; 

Operators >> and << indicate the direction of the action: << - write to the stream, >> - read from the stream. Do not forget that you can open a stream for reading and writing at the same time:

 std::stringstream stream(std::stringstream::in | std::stringstream::out); 
  • Look at the code, where is the error? why does nothing? - navi1893

To display the entire file on the screen, you must either read the lines in a loop sequentially into some string object that is immediately output to the console, for example:

 string str; ifstream fs ("f.txt"); while (getline (fs, str)) cout << str << endl; 

And you can immediately read the entire file from the stream buffer to the standard output

 cout << fs.rdbuf() << endl; 

PS In connection with the adjustment of the issue. If you write in Windows, then you can (tested in VS)

 #include <conio.h> ........ while ( fs >> str ) { while(_getch() != 'a') ; cout << str << endl; } 
  • Here is your code that displays all the words on the screen, but how to make it so that each time you press the "A" key, it displays the words alternately? I read that this can be done using a cycle, but I don’t know how. Will you help? - navi1893
  • Damn, then why the question says "line-by-line reading from the file"? So write while (fs >> str) cout << str << endl; - skegg
  • it is the same, everything takes one at a time - navi1893
  • one
    I give 10 minutes to reformulate the question, otherwise I’ll close it - skegg
  • one
    corrected. I think it will be clearer - navi1893