Until now, the example programs of previous sections provided very little interaction with the user, if any at all. Using the standard input and output library, we will be able to interact with the user by printing messages on the screen and getting the user's input from the keyboard.

C++ uses a convenient abstraction called streams to perform input and output operations in sequential media such as the screen or the keyboard. A stream is an object where a program can either insert or extract characters to/from it. We do not really need to care about many specifications about the physical media associated with the stream - we only need to know it will accept or provide characters sequentially.

The standard C++ library includes the header file iostream, where the standard input and output stream objects are declared.


Standard Output (cout)

By default, the standard output of a program is the screen, and the C++ stream object defined to access it is cout.

cout is used in conjunction with the insertion operator, which is written as << (two "less than" signs).

1
2
3
cout << "Output sentence"; // prints Output sentence on screen
cout << 120;               // prints number 120 on screen
cout << x;                 // prints the content of x on screen 


The << operator inserts the data that follows it into the stream preceding it. In the examples above it inserted the constant string Output sentence, the numerical constant 120 and variable x into the standard output stream cout. Notice that the sentence in the first instruction is enclosed between double quotes (") because it is a constant string of characters. Whenever we want to use constant strings of characters we must enclose them between double quotes (") so that they can be clearly distinguished from variable names. For example, these two sentences have very different results:

1
2
cout << "Hello";  // prints Hello
cout << Hello;    // prints the content of Hello variable 


The insertion operator (<<) may be used more than once in a single statement:

 
cout << "Hello, " << "I am " << "a C++ statement";


This last statement would print the message Hello, I am a C++ statement on the screen. The utility of repeating the insertion operator (<<) is demonstrated when we want to print out a combination of variables and constants or more than one variable:

 
cout << "Hello, I am " << age << " years old and my zipcode is " << zipcode;


If we assume the age variable to contain the value 24 and the zipcode variable to contain 90064 the output of the previous statement would be:

 
Hello, I am 24 years old and my zipcode is 90064 


It is important to notice that cout does not add a line break after its output unless we explicitly indicate it, therefore, the following statements:

1
2
cout << "This is a sentence.";
cout << "This is another sentence."; 


will be shown on the screen one following the other without any line break between them:

This is a sentence.This is another sentence. 
even though we had written them in two different insertions into cout. In order to perform a line break on the output we must explicitly insert a new-line character into cout. In C++ a new-line character can be specified as \n (backslash, n):

1
2
cout << "First sentence.\n";
cout << "Second sentence.\nThird sentence."; 


This produces the following output:

First sentence.
Second sentence.
Third sentence.

Additionally, to add a new-line, you may also use the endl manipulator. For example:

1
2
cout << "First sentence." << endl;
cout << "Second sentence." << endl; 


would print out:

First sentence.
Second sentence. 

The endl manipulator produces a newline character, exactly as the insertion of '\n' does, but it also has an additional behavior when it is used with buffered streams: the buffer is flushed. Anyway, cout will be an unbuffered stream in most cases, so you can generally use both the \n escape character and the endl manipulator in order to specify a new line without any difference in its behavior.

Standard Input (cin).

The standard input device is usually the keyboard. Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>) on the cin stream. The operator must be followed by the variable that will store the data that is going to be extracted from the stream. For example:

1
2
int age;
cin >> age; 


The first statement declares a variable of type int called age, and the second one waits for an input from cin (the keyboard) in order to store it in this integer variable.

cin can only process the input from the keyboard once the RETURN key has been pressed. Therefore, even if you request a single character, the extraction from cin will not process the input until the user presses RETURN after the character has been introduced.

You must always consider the type of the variable that you are using as a container with cin extractions. If you request an integer you will get an integer, if you request a character you will get a character and if you request a string of characters you will get a string of characters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// i/o example

#include <iostream>
using namespace std;

int main ()
{
  int i;
  cout << "Please enter an integer value: ";
  cin >> i;
  cout << "The value you entered is " << i;
  cout << " and its double is " << i*2 << ".\n";
  return 0;
}
Please enter an integer value: 702
The value you entered is 702 and its double is 1404.


The user of a program may be one of the factors that generate errors even in the simplest programs that use cin (like the one we have just seen). Since if you request an integer value and the user introduces a name (which generally is a string of characters), the result may cause your program to misoperate since it is not what we were expecting from the user. So when you use the data input provided by cin extractions you will have to trust that the user of your program will be cooperative and that he/she will not introduce his/her name or something similar when an integer value is requested. A little ahead, when we see the stringstream class we will see a possible solution for the errors that can be caused by this type of user input.

You can also use cin to request more than one datum input from the user:

 
cin >> a >> b;


is equivalent to:

1
2
cin >> a;
cin >> b;


In both cases the user must give two data, one for variable a and another one for variable b that may be separated by any valid blank separator: a space, a tab character or a newline.

cin and strings

We can use cin to get strings with the extraction operator (>>) as we do with fundamental data type variables:

 
cin >> mystring;


However, as it has been said, cin extraction stops reading as soon as if finds any blank space character, so in this case we will be able to get just one word for each extraction. This behavior may or may not be what we want; for example if we want to get a sentence from the user, this extraction operation would not be useful.

In order to get entire lines, we can use the function getline, which is the more recommendable way to get user input with cin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// cin with strings
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string mystr;
  cout << "What's your name? ";
  getline (cin, mystr);
  cout << "Hello " << mystr << ".\n";
  cout << "What is your favorite team? ";
  getline (cin, mystr);
  cout << "I like " << mystr << " too!\n";
  return 0;
}
What's your name? Juan Soulie
Hello Juan Soulie.
What is your favorite team? The Isotopes
I like The Isotopes too!


Notice how in both calls to getline we used the same string identifier (mystr). What the program does in the second call is simply to replace the previous content by the new one that is introduced.

stringstream

The standard header file <sstream> defines a class called stringstream that allows a string-based object to be treated as a stream. This way we can perform extraction or insertion operations from/to strings, which is especially useful to convert strings to numerical values and vice versa. For example, if we want to extract an integer from a string we can write:

1
2
3
string mystr ("1204");
int myint;
stringstream(mystr) >> myint;


This declares a string object with a value of "1204", and an int object. Then we use stringstream's constructor to construct an object of this type from the string object. Because we can use stringstream objects as if they were streams, we can extract an integer from it as we would have done on cin by applying the extractor operator (>>) on it followed by a variable of type int.

After this piece of code, the variable myint will contain the numerical value 1204.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// stringstreams
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main ()
{
  string mystr;
  float price=0;
  int quantity=0;

  cout << "Enter price: ";
  getline (cin,mystr);
  stringstream(mystr) >> price;
  cout << "Enter quantity: ";
  getline (cin,mystr);
  stringstream(mystr) >> quantity;
  cout << "Total price: " << price*quantity << endl;
  return 0;
}
Enter price: 22.25
Enter quantity: 7
Total price: 155.75


In this example, we acquire numeric values from the standard input indirectly. Instead of extracting numeric values directly from the standard input, we get lines from the standard input (cin) into a string object (mystr), and then we extract the integer values from this string into a variable of type int (quantity).

Using this method, instead of direct extractions of integer values, we have more control over what happens with the input of numeric values from the user, since we are separating the process of obtaining input from the user (we now simply ask for lines) with the interpretation of that input. Therefore, this method is usually preferred to get numerical values from the user in all programs that are intensive in user input.

Constants are expressions with a fixed value.

Literals

Literals are the most obvious kind of constants. They are used to express particular values within the source code of a program. We have already used these previously to give concrete values to variables or to express messages we wanted our programs to print out, for example, when we wrote:

 
a = 5;


the 5 in this piece of code was a literal constant.

Literal constants can be divided in Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values.

Integer Numerals


1
2
3
1776
707
-273


They are numerical constants that identify integer decimal values. Notice that to express a numerical constant we do not have to write quotes (") nor any special character. There is no doubt that it is a constant: whenever we write 1776 in a program, we will be referring to the value 1776.

In addition to decimal numbers (those that all of us are used to using every day), C++ allows the use of octal numbers (base 8) and hexadecimal numbers (base 16) as literal constants. If we want to express an octal number we have to precede it with a 0 (a zero character). And in order to express a hexadecimal number we have to precede it with the characters 0x(zero, x). For example, the following literal constants are all equivalent to each other:

1
2
3
75         // decimal
0113       // octal
0x4b       // hexadecimal 


All of these represent the same number: 75 (seventy-five) expressed as a base-10 numeral, octal numeral and hexadecimal numeral, respectively.

Literal constants, like variables, are considered to have a specific data type. By default, integer literals are of type int. However, we can force them to either be unsigned by appending the u character to it, or long by appending l:

1
2
3
4
75         // int
75u        // unsigned int
75l        // long
75ul       // unsigned long 


In both cases, the suffix can be specified using either upper or lowercase letters.

Floating Point Numbers

They express numbers with decimals and/or exponents. They can include either a decimal point, an e character (that expresses "by ten at the Xth height", where X is an integer value that follows the e character), or both a decimal point and an e character:

1
2
3
4
3.14159    // 3.14159
6.02e23    // 6.02 x 10^23
1.6e-19    // 1.6 x 10^-19
3.0        // 3.0 


These are four valid numbers with decimals expressed in C++. The first number is PI, the second one is the number of Avogadro, the third is the electric charge of an electron (an extremely small number) -all of them approximated- and the last one is the number three expressed as a floating-point numeric literal.

The default type for floating point literals is double. If you explicitly want to express a float or a long double numerical literal, you can use the f or l suffixes respectively:

1
2
3.14159L   // long double
6.02e23f   // float 


Any of the letters that can be part of a floating-point numerical constant (e, f, l) can be written using either lower or uppercase letters without any difference in their meanings.

Character and string literals

There also exist non-numerical constants, like:

1
2
3
4
'z'
'p'
"Hello world"
"How do you do?" 


The first two expressions represent single character constants, and the following two represent string literals composed of several characters. Notice that to represent a single character we enclose it between single quotes (') and to express a string (which generally consists of more than one character) we enclose it between double quotes (").

When writing both single character and string literals, it is necessary to put the quotation marks surrounding them to distinguish them from possible variable identifiers or reserved keywords. Notice the difference between these two expressions:

1
2
x
'x'


x alone would refer to a variable whose identifier is x, whereas 'x' (enclosed within single quotation marks) would refer to the character constant 'x'.

Character and string literals have certain peculiarities, like the escape codes. These are special characters that are difficult or impossible to express otherwise in the source code of a program, like newline (\n) or tab (\t). All of them are preceded by a backslash (\). Here you have a list of some of such escape codes:

\nnewline
\rcarriage return
\ttab
\vvertical tab
\bbackspace
\fform feed (page feed)
\aalert (beep)
\'single quote (')
\"double quote (")
\?question mark (?)
\\backslash (\)

For example:

1
2
3
4
'\n'
'\t'
"Left \t Right"
"one\ntwo\nthree" 


Additionally, you can express any character by its numerical ASCII code by writing a backslash character (\) followed by the ASCII code expressed as an octal (base-8) or hexadecimal (base-16) number. In the first case (octal) the digits must immediately follow the backslash (for example \23 or \40), in the second case (hexadecimal), an x character must be written before the digits themselves (for example \x20 or \x4A).

String literals can extend to more than a single line of code by putting a backslash sign (\) at the end of each unfinished line.

1
2
"string expressed in \
two lines" 


You can also concatenate several string constants separating them by one or several blank spaces, tabulators, newline or any other valid blank character:

 
"this forms" "a single" "string" "of characters"


Finally, if we want the string literal to be explicitly made of wide characters (wchar_t type), instead of narrow characters (char type), we can precede the constant with the L prefix:

 
L"This is a wide character string"


Wide characters are used mainly to represent non-English or exotic character sets.

Boolean literals

There are only two valid Boolean values: true and false. These can be expressed in C++ as values of type bool by using the Boolean literals true and false.

Defined constants (#define)

You can define your own names for constants that you use very often without having to resort to memory-consuming variables, simply by using the #define preprocessor directive. Its format is:

#define identifier value
For example:

1
2
#define PI 3.14159
#define NEWLINE '\n' 


This defines two new constants: PI and NEWLINE. Once they are defined, you can use them in the rest of the code as if they were any other regular constant, for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// defined constants: calculate circumference

#include <iostream>
using namespace std;

#define PI 3.14159
#define NEWLINE '\n'

int main ()
{
  double r=5.0;               // radius
  double circle;

  circle = 2 * PI * r;
  cout << circle;
  cout << NEWLINE;

  return 0;
}
31.4159


In fact the only thing that the compiler preprocessor does when it encounters #define directives is to literally replace any occurrence of their identifier (in the previous example, these were PI and NEWLINE) by the code to which they have been defined (3.14159 and '\n' respectively).

The #define directive is not a C++ statement but a directive for the preprocessor; therefore it assumes the entire line as the directive and does not require a semicolon (;) at its end. If you append a semicolon character (;) at the end, it will also be appended in all occurrences of the identifier within the body of the program that the preprocessor replaces.

Declared constants (const)

With the const prefix you can declare constants with a specific type in the same way as you would do with a variable:

1
2
const int pathwidth = 100;
const char tabulator = '\t';


Here, pathwidth and tabulator are two typed constants. They are treated just like regular variables except that their values cannot be modified after their definition.



Galera novo site de Relacionamento Melhor do facebook e orkut Que,
NAS ATUALIZAÇÕES de Amigos te Artigos de blogs ex: filmes musicas Programas e Muito Mais.
 Rede de Amizades, Grupos de Amigos ... Muito bom MESMO .. Acessem e faca Perfil Seu  www.orfury.com

Após instalar o Apache na porta 8080 do meu note  (a porta 80 já está tomada pelo IIS) me deparei com a seguinte visão:






























De cara nota-se que o meu Apache Service Monitor simplesmente Has no service at all!! Como não sei o quão comum é este comportamento, apesar de a solução do problema não ter me tomado lá muito tempo, achei interessante torna-la pública. O esquema é bem simples:
  1. Abra o prompt de comando
  2. Navege até o diretório:  [Diretório de instalação do Apache]\bin
  3. Execute o seguinte comando:
    1. httpd -k install
    2. httpd -k start
  4. Algo similar à imagem abaixo deverá aparecer:




                                            SUCESSO!!!

Agora o seu Monitor de serviços do apache deve exibir algo parecido com:















qual quer duvida comenta ai !!!!
Valew galera.....

Muita gente me perguntou sobre o cURL e alguns pediam um tutorial mais básico e detalhado… então vamos lá!
No PHP existem quatro formas de você acessar uma URL externa: usando a função fopen(), usando a função fsockopen(), usando a biblioteca cURL e usando a classe HTTP_Request. Cada uma dessas formas tem o seu uso específico mas todas podem ser usadas, de forma geral, pra mesma coisa. Eu, pessoalmente, prefiro e recomendo o uso da biblioteca cURL pelo seu poder e facilidade de uso.
Para poder usar o cURL no seu site/sistema você precisa que a biblioteca esteja instalada e habilitada, então vamos a um tutorial rápido de como fazer isso.. Se você já sabe que tem o cURL instalado no seu servidor, é só pular para o capitulo “Uso básico do cURL”.

Verificando se o cURL está instalado

Recomendo que antes de sair tentando instalar a cURL, verifique se ela já não está habilitada no seu servidor… Crie um arquivo .php com o seguinte conteúdo:
<?php
 // Exibe informações relativas ao PHP e suas extensões
 phpinfo();
?>
Acesse esse arquivo pelo seu navegador e procure por “cURl support” se encontrar algo significa que você tem o cURL instalado e pode pular o próximo capitulo.

Instalando o cURL

Para instalá-lo é bem simples, basta acessar o seu arquivo php.ini que geralmente fica dentro da pasta php do seu servidor (sim, você precisa ter acesso a esse arquivo) e procure por essa linha:
;extension=php_curl.dll
Agora remova o ponto-e-vírgula (;) do começo da linha, reinicie o seu servidor e voila! Você acabou de instalar o cURL no seu sistema.
----------------------------------------------------------------------------------------------

Uso básico do cURL

Bom, primeiro de tudo, vamos o script mais simples que você pode usar para pegar a resposta de um site (que nesse caso, é o arquivo robots.txt aqui do blog):
<?php
 // Inicia o cURL acessando uma URL
 $cURL = curl_init('http://blog.thiagobelem.net/robots.txt');
 // Define a opção que diz que você quer receber o resultado encontrado
 curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
 // Executa a consulta, conectando-se ao site e salvando o resultado na variável $resultado
 $resultado = curl_exec($cURL);
 // Encerra a conexão com o site
 curl_close($cURL);
?>


Depois de executar esse script, o conteúdo da variável $resultado será exatamente o conteúdo do meu arquivo robots.txt. Você pode usar esse método para pegar o HTML resultado de qualquer site e etc.

A função curl_setopt() permite que você defina uma série de opções MUITO úteis para o uso do cURL, recomendo que vocês vejam a documentação dela para dar uma olhada na lista completa.

Verificando se um site está no ar e acessível

Com o script que vou mostrar agora você vai poder acessar qualquer endereço ou URL pública e descobrir se ele retorna erro 404 (página não encontrada) ou não, baseando-se no código HTTP de resposta:
<?php
 $cURL = curl_init('http://www.sitequenaoexiste.net.br');
 curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

 // Seguir qualquer redirecionamento que houver na URL
 curl_setopt($cURL, CURLOPT_FOLLOWLOCATION, true);

 $resultado = curl_exec($cURL);

 // Pega o código de resposta HTTP
 $resposta = curl_getinfo($cURL, CURLINFO_HTTP_CODE);

 curl_close($cURL);

 if ($resposta == '404') {
  echo 'O site está fora do ar (ERRO 404)!';
 } else {
  echo 'Parece que está tudo bem...';
 }
?>
Adicionei também uma opção nova (CURLOPT_FOLLOWLOCATION) que vai permitir que o cURL siga todos os redirects que houverem na URL. Por exemplo, se estivermos usando o TintURL é preciso seguir o redirecionamento depois de acessar a url reduzida para chegar na URL final.

Enviando dados para formulários (via método POST)

Suponhamos que você queira testar o cURL enviando dados para um formulário, como se você tivesse digitando os dados e dando submit no formulário. Você vai precisar de duas coisas: a lista dos nomes (names) dos campos e o action do formulário (que é pra onde os dados são enviados)… Depois é só montar um script parecido com esse:
<?php
 // Aqui entra o action do formulário - pra onde os dados serão enviados
 $cURL = curl_init('http://www.meusite.com.br/envia.php');
 curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

 // Definimos um array seguindo o padrão:
 //  '<name do input>' => '<valor inserido>'
 $dados = array(
  'nome' => 'Thiago Belem',
  'email' => 'contato@thiagobelem.net',
  'mensagem' => 'Testando o cURL!'
 );

 // Iremos usar o método POST
 curl_setopt($cURL, CURLOPT_POST, true);
 // Definimos quais informações serão enviadas pelo POST (array)
 curl_setopt($cURL, CURLOPT_POSTFIELDS, $dados);

 $resultado = curl_exec($cURL);
 curl_close($cURL);
?>
Mas suponhamos que você testou o script e reparou que algo deu errado.. E depois de fazer o seu trabalho de casa, descobriu que o site permite apenas dados vindos do próprio site (ou seja, ele verifica o REFERER que é o endereço da página na qual os dados foram inseridos). Então, você ajusta o seu script da seguinte maneira:
<?php
 $cURL = curl_init('http://www.meusite.com.br/envia.php');
 curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

 $dados = array(
  'nome' => 'Thiago Belem',
  'email' => 'contato@thiagobelem.net',
  'mensagem' => 'Testando o cURL!'
 );

 curl_setopt($cURL, CURLOPT_POST, true);
 curl_setopt($cURL, CURLOPT_POSTFIELDS, $dados);

 // O site só permite requisições vindas do próprio site:
 // Definimos então o REFERER como sendo a página do formulário de contato
 curl_setopt($cURL, CURLOPT_REFERER, 'http://www.meusite.com.br/contato.php');

 $resultado = curl_exec($cURL);
 curl_close($cURL);
?>


Vou parar por aqui… Sei que existem vários outros usos e possíveis exemplos do cURL, mas a minha intenção era apenas mostrar como é simples e rápido usar todos os recursos do cURL… Se você misturar os comandos certos com as funções certas, vai poder fazer um sistema bem legal.
Espero que tenham gostado! :D