Chaîne de caractères la plus longue
#include<stdio.h>
#define MAXSIZE 100 /*max size line */
#define END '!'
int readLine(char s[], int lim);
void copyLine(char dest[], char src[]);
/*
read the input char and save the char into s
return : s[] size */
int readLine(char s[], int lim)
{
int c; /* char read */
int i;
for (i=0; i<lim-1 && ((c=getchar())!=END) && c != '\n';
++i) {
s[i] = c;
}
if (c=='\n') {
s[i] = c;
++i;
}
s[i] = '\0'; /* to finalize the line */
return i;
}
/*
copy src to dest
*/
void copyLine(char dest[], char src[])
{
int i=0;
while ((dest[i] = src[i]) != '\0') {
++i;
}
}
int main(int argc, char** argv)
{
int l;
int max; /* size of the longest line current read */
char line[MAXSIZE];
char longestLine[MAXSIZE];
max = 0;
while ((l = readLine(line, MAXSIZE)) > 0) {
if (l > max) {
max = l;
copyLine(longestLine, line);
}
}
if (max > 0)
printf("Longest line is : %s", longestLine);
return 0;
}
Pour finir la saisie, sur une ligne vierge, saisir le caractère "!", paramétrable en changeant la valeur de END en define.
Exécution
$gcc copy.c -o copy $chmod +x copy $./copy azerty azertyuiop azer ! Longest line is : azertyuiop $
copy.c