Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to convert a string to a integer in C

Hello, guys, i am having so difficulties with a problem.

Each string has a name of a film followed by a date that corresponds to the release date of the movie

The aim is to create an array of strings of movies that are prior to a certain date..

For example

The Matrix (20xx)
Inception(20xx)
Mission Impossible(20xx)

And the objective is to put in a array of strings all movies prior to 2008

How can i do it? I was thinking using atoi but i don't know how to do it because i just want a part of the string to be converted to int and not the entire string


1 Answer
Pythonista

First extract characters from left bracket '(' using strchr() function.

char *name="The Matrix(1999)";
char *ps;
ps=strchr(name,'(');

Then add each character within brackets () to an char array

char y[5]=""; int  p;
for (p=1;p<strlen(ps+1);p++)
{
y[p-1]=ps[p];
}
y[4]='\0';

Lastly convert resultant string to integer using atoi() function

year=atoi(y);
printf("year=%d",year);

You can now apply required filters ti create array of strings of all movies prior to 2008

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.