Functions for get user input from stdin (shell)

Hi
What function are there in order to get user input from stdin (shell) in Linux ?

Thanks in advance
cin
???
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
	char *str,*s;

	//Allocate memory and store the first address in str.
	str=calloc(256,sizeof(char));

	//Read up to 255 characters (last character will be 0, always) from stdin.
	fgets(str,256,stdin);

	//Strip off return characters.
	for(s=str;*s;s++)if(*s=='\n'||*s=='\r')break;*s=0;

	//Output the results in pretty quotes.
	printf("\nYou entered: \"%s\"\n",str);

	free(str);
	return 0;
}


If you wanted to, very specifically, get input from stdin. Note that that is C, and probably won't compile in a C++ compiler if you don't cast (char*) on the calloc().

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>	//std::cout
#include <string>	//std::string, std::getline();

using namespace std;
int main(){
	string buffer;

	//Get a line of input and output the results
	getline(cin,buffer);
	cout<<"You entered: \""<<buffer<<"\""<<endl;

	return 0;
}


Or something more like that if you actually want C++ streams instead of C-style file access. You could use cin like the previous poster suggested, but it's often better to read a line at a time and then parse the text you're looking for from it.

1
2
3
4
...
string buffer;
cin >> buffer;
...
Last edited on
Topic archived. No new replies allowed.