如何用符号分析组织无限循环呢?

iol*_*700 0 c++ loops

我需要在其中组织带有符号分析的无限循环.在使用的CI中fgets(buf, N, stdin),假设bufbuf[10].用户可以输入任意长度的字符串,我可以通过分解输入并检查长度为10的部分来分析它.如何在不使用C库的情况下在C++中实现它.如果你不明白我的意思,抱歉我的英语

Poe*_*odu 5

在C++中,您应该std::cin从标准输入中读取.

// #include <iostream>

do
{
    char buf[10]{}; // create array of 10 bytes filled with zeros.
    std::cin.read(buf, 10); // read 10 bytes

    // at this point you should check if std::cin.read succeeded.
    // otherwise you will be reading zeros.

    std::streamsize numRead = std::cin.gcount(); // obtain number of read bytes.
    std::cout << numRead << " " << buf << std::endl; // some printing.
}while(std::cin);
Run Code Online (Sandbox Code Playgroud)

  • 使用`do while`可能会更好,因为即使还有剩余的字节需要分析,最后一次读取也会返回false.另外一些解释会很好,因为只有代码的答案是不受欢迎的 (3认同)