It is necessary several times to enter and display a string that contains spaces. How many times to enter-output is at the discretion of the user. Tried it, but not working.

#include <conio.h> #include <string> #include <iostream> using namespace std; int main () { string str; int i = 0; do { cout << "str:"; getline(cin, str, '\n'); cout << "str:" << str << endl; cout << "repeat (1-yes/0-no)"; cin >> i; } while (i == 1); getch(); return 0; } 

The program is compiled and the cycle repeats, but when I assign the value i to variable 1, no further line is entered. It looks like this:

 Input text: this is text Text: this is text repeat (1/0):1 Input text: Text repeat (1/0):1 Input text: Text repeat (1/0):1 

And so on until I get out of the cycle. Tell me what the error is and how to fix it.

  • and what if you add cin.ignore () after cin >> i? - KryDos

4 answers 4

@kop_vlad , no mysticism.

The fact is that all the characters after the number and '\n' along with them after entering 1 in


remain in the input stream.

In reality, in your case, there will most likely be \ r \ n characters.

Just add


immediately before while(i==1); and it will work.

    It is generally not recommended to use the std :: getline and >> operator.

    Here is the answer to your question.

    • Thank. The insert cin.ignore () helped. - kop_vlad
     #include <iostream> using namespace std; int main (){ string str = "aaaaa\nbbbb bbbbb\nccccc cccccc ccccc\ndddd \neeeee\n", buf; for (int i = 0; i < str.length(); i++){ if (str[i] != '\n'){ buf.push_back(str[i]); } else { for (int i = 0; i < buf.length(); i++){ if (buf[i] == ' '){ cout << "stroka: " << buf << " <--- soderzit probely!" << endl; break; } } buf = ""; } } return 0; } 

      Reading from the keyboard lines consisting of words separated by spaces can be performed using the following program fragment.

       #include "stdafx.h" #include <string> #include <iostream> // <Другие директивы препроцессора> #define SIZE 80 using namespace std; void _tmain() { string str; // Объявление строки типа string char stc[SIZE]; // Объявление стандартной строки языка С++ cout << “Введите строку из нескольких слов \n”; getline (cin, str); // Чтение строки до нажатия на клавишу ENTER strcpy (stc, str.c_str()); // Копирование с преобразованием . . . }