R
R
romentigo2019-01-12 22:52:06
C++ / C#
romentigo, 2019-01-12 22:52:06

C++ - why does the program write the first line to the file empty?

Hello! I came to such a dead end: no matter what line I enter, the first line is written to the file empty, and the last line entered is not written. I made a crutch in for, increasing the number of repetitions by 1 so that the last line could be written, but because of this crutch, I have to make other crutches in order for the program to work normally. It is very necessary to understand why such a shift occurs in the lines when writing to a file, so that this "tumor" in the code can be removed.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <conio.h>

using namespace std;

void Write(int strings)
{
  ofstream file("Строки.txt");
  char temp[100];
  if (!file.is_open())
  {
    cout << "По какой-то причине, файл не может быть открыт." << endl;
  }
  else
  {
    cout << "Вводите строки:" << endl;
    for (int i = 0; i <= strings; i++)
    {
      cin.getline(temp, 100);
      file << temp << "\r\n";
    }		
  }
  file.close();
}

void Read(int strings)
{
  ifstream file("Строки.txt");
  char temp[100];
  char check[] = { ',', '.', '!', '?', '-' };
  int count = 0;

  if (!file.is_open())
  {
    cout << "По какой-то причине, файл не может быть открыт." << endl;
  }
  else
  {
    cout << "\nСчитываю строки...";
    for (int i = 0; i <= strings; i++)
    {
      file.getline(temp, 100);
      cout << temp << endl;
      cout << temp[strlen(temp) - 2] << endl;
    } 
    
  }
  file.close();
}

int main()
{
  setlocale(LC_ALL, "rus");
  
  int strings = 0;

  cout << "Количество строк: ";
  cin >> strings;
  Write(strings);
  Read(strings);

  system("pause");
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
German, 2019-01-12
@romentigo

Wow, this is indeed a problem, I found out why this happens - in the stream from cin >> strings; line break remains (After pressing Enter, \n is passed to the stream, which ends it).
cin.get() after cin >> strings .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question