制作文本文件,按字符串键入字符串

问题描述 投票:0回答:2

我想制作文本文件,逐字符串填充他,直到空字符串。但是,不知怎的,我有无限的输入,我需要做什么才能逃脱无限循环?

这是我的代码:

  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;
    }
}
c++ file
2个回答
2
投票

使用cin >> buf,您一次只能阅读一个单词。使用std::getline更容易:

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;
    }
}

如果您被迫使用固定缓冲区,则需要在数据中搜索\n\n\n是C ++中的新行符号。


0
投票

您需要循环迭代直到文件结束。

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();
© www.soinside.com 2019 - 2024. All rights reserved.