簡體   English   中英

標准輸入while循環不會退出c ++

[英]Standard input while loop won't exit c++

我正在嘗試從標准輸入(unix中的[a.out <text.txt])中讀取內容,並且使用了以下兩個代碼塊:

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

    int main(){
    char c;
    while (cin.getchar(c)){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循環不退出可能與隱含性有關,但是您可以將其視為替代方法。

我認為這可能是您的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();
}

我能想到的最簡單的方法是使用類似以下的內容

#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應該起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM