Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reading from stdin in c++

Tags:

c++

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?

like image 348
krisdigitx Avatar asked May 05 '12 17:05

krisdigitx


People also ask

What does it mean to read from stdin?

Short for standard input, stdin is an input stream where data is sent to and read by a program. It is a file descriptor in Unix-like operating systems, and programming languages, such as C, Perl, and Java. Below, is an example of how STDIN could be used in Perl.

What is the use of stdin in C?

fflush() is typically used for output stream only. Its purpose is to clear (or flush) the output buffer and move the buffered data to console (in case of stdout) or disk (in case of file output stream).

Does scanf read from stdin?

Description. The scanf() function reads data from the standard input stream stdin into the locations given by each entry in argument-list. Each argument must be a pointer to a variable with a type that corresponds to a type specifier in format-string.


1 Answers

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; } 
like image 121
loganfsmyth Avatar answered Sep 29 '22 09:09

loganfsmyth