2011-03-26 16 views
8

मैं निम्नलिखित कोड का उपयोग कर रहा साथ इनपुट पहुंचाया:पढ़ना सी ++

#include <iostream> 
using namespace std; 

int main(int argc, char **argv) { 
    string lineInput = " "; 
    while(lineInput.length()>0) { 
     cin >> lineInput; 
     cout << lineInput; 
    } 
    return 0; 
} 

निम्न आदेश के साथ: echo "Hello" | test.exe

Thes परिणाम एक infinate पाश मुद्रण "हैलो" है। मैं इसे एक "हैलो" कैसे पढ़ और प्रिंट कर सकता हूं?

उत्तर

22
string lineInput; 
while (cin >> lineInput) { 
    cout << lineInput; 
} 

तुम सच में पूर्ण लाइनों चाहते हैं, का उपयोग करें:

string lineInput; 
while (getline(cin,lineInput)) { 
    cout << lineInput; 
} 
+0

इससे आपको उपयोगकर्ता इनपुट करने की अनुमति नहीं मिलती है। – UpmostScarab

10

जब cin निकालने के लिए विफल रहता है, यह लक्ष्य चर नहीं बदलता है। तो जो भी प्रोग्राम आपके प्रोग्राम को सफलतापूर्वक पढ़ता है वह lineInput में फंस गया है।

आपको cin.fail(), और Erik has shown the preferred way to do that जांचना होगा।