0

Работаем с файлом 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; }

Den
  • 49
  • когда я использую вместо getline(cin, msg) cin >> msg; то всё работает, но проблема в том, что cin >> считывает до первого проблема, а мне надо всю строку – Den Nov 29 '20 at 17:17

1 Answers1

2

После команды 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');

getline() skipping first even after clear()

istream::ignore and getline() confusion

AlexGlebe
  • 17,227