Answer the question
In order to leave comments, you need to log in
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question