标准输入,而循环不会退出 c++

Standard input while loop won't exit c++

本文关键字:退出 c++ 循环 标准输入      更新时间:2023-10-16

我正在尝试从标准输入([a.out <text.txt]在unix中读取),并且我使用了以下两个代码块:>

    int main(){
    while (!cin.eof()){ReadFunction()} 
    OutputFunction();}

    int main(){
    char c;
    while (cin.getchar(c)){ReadFunction()} 
    OutputFunction();}

这两个循环都正确执行读取函数,但它们都没有退出循环并执行输出函数。如何从标准输入中逐个字符读取,然后执行输出函数?

我认为这可能是您的 ReadFunction() 中的一个问题。如果不读取字符,流将不会前进,并且会卡在循环中。
以下代码有效:-

#include <iostream>
#include <string>
using namespace std;
string s;
void ReadFunction()
{
    char a;
    cin >> a;
    s = s + a;
}
void OutputFunction()
{
    cout <<"Output : n" << s;
}
int main()
{
    while (!cin.eof()){ReadFunction();}
    OutputFunction();
}
已知

cin.eof()是不可信的。如果经常会返回不准确的结果。无论哪种方式,都建议您从文件中复制所有数据(您说这是您的标准输入),然后从中获取字符。我建议使用 std::stringstream 来保存文件中的数据,然后使用 std::getline()。我没有编写Unix的经验,但您通常可以尝试这样的事情:

#include <string>
#include <sstream>
#include <iostream>
int main() {
    std::string strData;
    std::stringstream ssData;
    while (std::getline(in /*Your input stream*/, strData))
        ssData << strData;
    ssData.str().c_str();   // Your c-style string
    std::cout << (ssData.str())[0];   // Write first char
    return 0;
}

至于为什么你的while循环没有退出可能与暗示有关,但你可以考虑将其作为一种替代方案。

我能想到的最简单的方法是使用如下所示的东西

#include <cstdio>
int main() {
    char c;
    while((c = getchar()) != EOF) { // test if it is the end of the file
        // do work
    }
    // do more work after the end of the file
    return 0;
}

与您的唯一真正的区别是,上面的代码测试c以查看它是否是文件的末尾。然后像./a.out < test.txt这样的东西应该起作用。