getline для работы с файлами не работает
Работаем с файлом MyFile.txt. Почему-то после ввода 1 консоль не ждёт, чтобы я ввёл текст (из-за getline(cin, msg)), а игнорирует это и заканчивает свою работу.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string path = "MyFile.txt";
fstream fs;
fs.open(path, fstream::in | fstream::out | fstream::app);
if (fs.is_open())
{
int value;
string msg;
cout << "Type 1 to write sth!" << endl;
cin >> value;
if (value == 1)
{
getline(cin, msg);
fs << msg;
}
}
fs.close();
system("pause");
return 0;
}
Ответы (1 шт):
После команды cin >> value нужно убрать оставшийся в буфере конец строки.
cin >> value ;
cin . ignore ( std::numeric_limitsstd::streamsize::max(), '\n');
Ответ взят из источников информации :
https://en.cppreference.com/w/cpp/string/basic_string/getline
Notes When consuming whitespace-delimited input (e.g. int n; std::cin >> n;) any whitespace that follows, including a newline character, will be left on the input stream. Then when switching to line-oriented input, the first line retrieved with getline will be just that whitespace. In the likely case that this is unwanted behaviour, possible solutions include:
An explicit extraneous initial call to getline
Removing consecutive whitespace with std::cin >> std::ws
Ignoring all leftover characters on the line of input with cin.ignore(std::numeric_limitsstd::streamsize::max(), '\n');
https://stackoverflow.com/questions/12186568/getline-skipping-first-even-after-clear
https://coderoad.ru/8105847/istream-ignore-и-getline-путаница