3.2 strstr() example
3.2 strstr() example
Let’s back to the fact that GCC sometimes can use part of string:1.5.3 on page 18.
Thestrstr()C/C++ standard library function is used to find any occurrence in a string. This is what we will
do:
#include <string.h>
#include <stdio.h>
int main()
{
char s="Hello, world!";
char w=strstr(s, "world");
printf ("%p, [%s]\n", s, s);
printf ("%p, [%s]\n", w, w);
};
The output is:
0x8048530, [Hello, world!]
0x8048537, [world!]
The difference between the address of the original string and the address of the substring thatstrstr()has
returned is 7. Indeed, “Hello, ” string has length of 7 characters.
Theprintf()function during second call has no idea there are some other characters before the passed
string and it prints characters from the middle of original string till the end (marked by zero byte).
3.3 Temperature converting
Another very popular example in programming books for beginners is a small program that converts
Fahrenheit temperature to Celsius or back.
C=
5 ⋅(F−32)
9
We can also add simple error handling: 1) we must check if the user has entered a correct number; 2) we
must check if the Celsius temperature is not below− 273 (which is below absolute zero, as we may recall
from school physics lessons).
Theexit()function terminates the program instantly, without returning to thecallerfunction.
3.3.1 Integer values
#include <stdio.h>
#include <stdlib.h>
int main()
{
int celsius, fahr;
printf ("Enter temperature in Fahrenheit:\n");
if (scanf ("%d", &fahr)!=1)
{
printf ("Error while parsing your input\n");
exit(0);
};
celsius = 5 * (fahr-32) / 9;
if (celsius<-273)
{
printf ("Error: incorrect temperature!\n");