lezen uit stdin in c++

Ik probeer te lezen van stdin met C++, met deze code

#include <iostream>
using namespace std;
int main() {
    while(cin) {
        getline(cin, input_line);
        cout << input_line << endl;
    };
    return 0;
}

wanneer ik compileer, krijg ik deze foutmelding..

[root@proxy-001 krisdigitx]# g++ -o capture -O3 capture.cpp
capture.cpp: In function âint main()â:
capture.cpp:6: error: âinput_lineâ was not declared in this scope

Enig idee wat er ontbreekt?


Antwoord 1, autoriteit 100%

U heeft de variabele input_lineniet gedefinieerd.

Voeg dit toe:

string input_line;

En voeg dit toe.

#include <string>

Hier is het volledige voorbeeld. Ik heb ook de puntkomma verwijderd na de while-lus, en je zou getlinebinnen de while moeten hebben om het einde van de stream correct te detecteren.

#include <iostream>
#include <string>
int main() {
    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
}

Antwoord 2

//declaration:    
    int i2;
    double d2;
    string s2;
//reading by keyboard
    cin >> i2;
    cin >> d2;
    cin.get();
    getline(cin, s2);
//printing:
    cout << i+i2 << endl;    
    cout<< std::fixed <<std::setprecision(1)<< d + d2 << endl;
    cout << s << s2;

u kunt deze code uitvoeren:

#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
int main() {
    int i = 4;
    double d = 4.0;
    string s = "hi ";
    int i2;
    double d2;
    string s2;
    cin >> i2;
    cin >> d2;
    cin.get();
    getline(cin, s2);
    cout << i+i2 << endl;
    cout<< std::fixed <<std::setprecision(1)<< d + d2 << endl;
    cout << s << s2;
    return 0;
}

Other episodes