0

I want to make text file, filling him string by string, until empty string. But, somehow I have infinite input, what conidition need I make to escape infinite loop?

Here is my code:

  fstream f;
f.open("text1.txt", ios::out);
bool flag = false;
while (!flag) {
    char buf[50];
    cin >> buf;
    if (strlen(buf)!=0 )
        f<<buf<<endl;
    else {
        f.close();
        flag = true;
    }
}
Tovarisch
  • 39
  • 2
  • 13
  • Possible duplicate of [tell cin to stop reading at newline](https://stackoverflow.com/questions/9673708/tell-cin-to-stop-reading-at-newline) – ggorlen Apr 12 '19 at 15:26

2 Answers2

2

With cin >> buf you are reading one word at a time. It's easier to use std::getline instead:

fstream f;
f.open("text1.txt", ios::out);
bool flag = false;
while (!flag) {
    string str;
    getline(cin, str);
    if (cin && !str.empty())
        f<<str<<endl;
    else {
        f.close();
        flag = true;
    }
}

If you are forced to use fixed buffer, you need to search for \n\n occurrence in a data. \n is a new line symbol in C++.

magras
  • 1,709
  • 21
  • 32
  • My complier somehow says that getline is undefined, a f< – Tovarisch Apr 12 '19 at 15:46
  • @Tovarisch, `std::getline` and `std::string` are defined in `` header. You are right about using `str` instead of `buf` in output. – magras Apr 12 '19 at 15:49
  • So there getline cant be used with char [ ]? – Tovarisch Apr 12 '19 at 15:54
  • @Tovarisch, there is a method [`std::basic_istream::getline()`](https://en.cppreference.com/w/cpp/io/basic_istream/getline) that can be used with char array like that `cin.getline(buf, buf_size)`. It will read until new line but no more than `buf_size` chars. – magras Apr 12 '19 at 16:01
0

You need to iterate while loop until end of file.

fstream f;
f.open("text1.txt", ios::out);
char buf[50];

while (cin >> buf)    // it becomes false when end of file reach. You can test it from keyboard by Ctrl+Z and then Enter
{
    f<<buf<<endl;
}
f.close();
Faruk Hossain
  • 1,205
  • 5
  • 12