Condition:

Input file name input.txt Output file name standard output

Given file input.txt, which contains the text. Write a program that will find the character that is in the middle of the file.

Input data format The input file contains no more than 10 ^ 7 characters with ASCII codes from 33 to 126.

Output Format You want to display the middle character of the input file on the screen. If the file has an even number of characters, the program should output two characters that are in the middle separated by spaces.

#include <iostream> #include <fstream> #include <string> #include <cstring> using namespace std; int main(){ string buf; short k=0, n = 0; ifstream infile; infile.open("middle.txt", ios::in); if(infile.is_open()){ infile >> buf; n = buf.size(); cout << n << endl; k = n/2; if(n%2 == 1) { cout << buf[k]; } else cout << buf[k-1] << " " << buf[k]; } else{ cout << "File error."<< endl; return 1; } infile.close(); return 0; } 

I solved the task, but I did not understand how to insert seekg / tellg here. If anyone knows, tell me. Thank.

  • one
    seekg/tellg and ios::binary when opened at your service :) Ah, the characters start at 33 - then even ios::binary not required ... - Harry
  • char * start = input.seekg (0, std :: ios_base :: beg), * endt = input.seekg (0, std :: ios_base :: end); and count the cycle between them number? - Trulimon
  • Become at the end of the file, get tellg , find the middle ... - Harry

0