reading from stdin in c++

C++

C++ Problem Overview


I am trying to read from stdin using C++, using this code

#include <iostream>
using namespace std;

int main() {
    while(cin) {
        getline(cin, input_line);
        cout << input_line << endl;
    };
    return 0;
}

when i compile, i get this error..

[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

Any ideas whats missing?

C++ Solutions


Solution 1 - C++

You have not defined the variable input_line.

Add this:

string input_line;

And add this include.

#include <string>

Here is the full example. I also removed the semi-colon after the while loop, and you should have getline inside the while to properly detect the end of the stream.

#include <iostream>
#include <string>

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

Solution 2 - C++

//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;

you can run this code:

#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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkrisdigitxView Question on Stackoverflow
Solution 1 - C++loganfsmythView Answer on Stackoverflow
Solution 2 - C++user7396942View Answer on Stackoverflow