473,625 Members | 3,093 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

is this correct

Q6: Write a function that accepts two strings. Count the number of
characters in each, and return a pointer to the longer string.
and please comment

/* LEN_STRING.C PROGRAM TO RETURN LONGEST STRING */
#include<stdio. h>
#include<string .h>

void length(char [ ], char [ ]);

int main(void)
{

char a[100];
char b[100];

printf("Enter string1\n");
fgets(a,100,std in);

printf("Enter string2\n");
fgets(b,100,std in);

length(a,b);

return 0;
}

void length(char string1[ ], char string2[ ])
{
char *line;

if((strlen(stri ng1)) > (strlen(string2 )))
{
line = string1;
printf("\nstrin g 1 is the longest\n%s\n", line);
}
else if(strlen(strin g1) < strlen(string2) )
{
line = string2;
printf("\nstrin g 2 is the longest\n%s\n", line);
}
else
printf("\nBoth strings are the same length\n");
}
Nov 14 '05 #1
28 2044
Darklight <ng******@netsc ape.net> writes:
Q6: Write a function that accepts two strings. Count the number of
characters in each, and return a pointer to the longer string.
and please comment

/* LEN_STRING.C PROGRAM TO RETURN LONGEST STRING */
#include<stdio. h>
#include<string .h>

void length(char [ ], char [ ]);
The question asks to return a pointer to the longer string, but your
`length' function returns nothing. Also, a better function name would be
something like `longer_string' , since that's what the function is
supposed to return.
int main(void)
{

char a[100];
char b[100];

printf("Enter string1\n");
fgets(a,100,std in);

printf("Enter string2\n");
fgets(b,100,std in);
If the user enters 100 or more characters after the first prompt, these
additional characters are read by the second `fgets' call.
length(a,b);

return 0;
}

void length(char string1[ ], char string2[ ])
{
char *line;

if((strlen(stri ng1)) > (strlen(string2 )))
{
line = string1;
printf("\nstrin g 1 is the longest\n%s\n", line);
}
else if(strlen(strin g1) < strlen(string2) )
{
line = string2;
printf("\nstrin g 2 is the longest\n%s\n", line);
}
else
printf("\nBoth strings are the same length\n");
}


It's probably a good idea not to do any output in the `length' function,
but just return a pointer to the longer string (as required in the
question). Do the output in `main' instead.

It is good that you thought about the case when both strings have the
same length, although the question doesn't specify what to do in this
case.

Calling `strlen' twice for each string could degrade the performance.
Use variables instead

const size_t len1 = strlen (string1);
const size_t len2 = strlen (string2);

and compare these.

The `line' variable is not really needed. In the block where you /know/
that `string1' is longer, you can just use `string1'. Likewise for
`string2'.

Finally, identifiers starting with `str' followed by a lowercase letter
are reserved for the implementation. Consider different names, e.g.
`str1' and `str2'.

Martin
--
,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
/ ,- ) http://www.zero-based.org/ ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. Debian, a variant of the GNU operating system. \_/
Nov 14 '05 #2
Darklight <ng******@netsc ape.net> writes:
Mail-Copies-To: ng******@netsca pe.net


You set the above header in your posting. This caused my newsreader to
send a mail copy of my reply to you, however it was returned due to an
invalid email address.

Don't set Mail-Copies-To to an invalid email address, please!

Martin
--
,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
/ ,- ) http://www.zero-based.org/ ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. Debian, a variant of the GNU operating system. \_/
Nov 14 '05 #3


Darklight wrote:
Q6: Write a function that accepts two strings. Count the number of
characters in each, and return a pointer to the longer string.
and please comment

void length(char [ ], char [ ]);


Looking at your requirements, one wonders what you want to
return should the lengths be equal.

Longing at your prototype, it does not meet the requirements
because it does not return anything. Also, since the strings
are not going to be modified, you can make the parameters
const char.

const char *length(const char *s1, const char *s2);

If it doesn't matter which string pointer is returned should
the lengths be equal, then the definition is simple.

#include <stdio.h>
#include <string.h>

const char *length(const char *string1, const char *string2)
{
return strlen(string1) >=strlen(string 2)?string1:stri ng2;
}

int main(void)
{
char *str1 = "Good Morning";
char *str2 = "Good Night";

printf("The longer of \"%s\" and \"%s\"\n"
"is \"%s\"\n",str1, str2,length(str 1,str2));
return 0;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #4
Is this any better

/* LEN_STRING1.C PROGRAM TO RETURN LONGEST STRING */
#include<stdio. h>
#include<string .h>

char *length(char [ ], char [ ]);

int main(void)
{

char a[100];
char b[100];
char *c;

printf("Enter string1\n");
fgets(a,100,std in);

printf("Enter string2\n");
fgets(b,100,std in);

c = length(a,b);

printf("\nThe longest string is %s\n",c);
return 0;
}

char *length(char str1[ ], char str2[ ])
{
char *line;

if((strlen(str1 )) > (strlen(str2)))
{
line = str1;
}
else
{
line = str2;
}

return line;
}
Nov 14 '05 #5

"Darklight" <ng******@netsc ape.net> wrote in message
/* LEN_STRING1.C PROGRAM TO RETURN LONGEST STRING */
#include<stdio. h>
#include<string .h>

char *length(char [ ], char [ ]);

int main(void)
{

char a[100];
char b[100];
char *c;

printf("Enter string1\n");
fgets(a,100,std in);

printf("Enter string2\n");
fgets(b,100,std in);
You still haven't fixed the fgets() problem. fgets() is actually quite a
difficult function to use.
c = length(a,b);

printf("\nThe longest string is %s\n",c);
return 0;
}

char *length(char str1[ ], char str2[ ])
It's much mode idiomatic to use the char *str1, char *str2 notation. The
pointers can also be const since they are not modified.
{
char *line;

if((strlen(str1 )) > (strlen(str2)))
{
line = str1;
}
else
{
line = str2;
}

return line;
}

You do need to know what is supposed to happen if the strings are of equal
length. This is an oversight in your specification.
Nov 14 '05 #6
Darklight <ng******@netsc ape.net> writes:
Mail-Copies-To: ng******@netsca pe.net
Once again, please don't do that.
Is this any better


Yes, it is better, although some of the comments you have received from
me and others still apply. :)

Martin
--
,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
/ ,- ) http://www.zero-based.org/ ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. Debian, a variant of the GNU operating system. \_/
Nov 14 '05 #7
Darklight wrote:
Q6: Write a function that accepts two strings. Count the number of
characters in each, and return a pointer to the longer string.
and please comment


Is this a homework? Cause if it is, you got it wrong..

In a homework situation, the tutor is probably suggesting that YOU
create the strlen() function and not to use the ready one...

--
Giannis Papadopoulos
http://dop.users.uth.gr/
University of Thessaly
Computer & Communications Engineering dept.
Nov 14 '05 #8
// here's my solution to this homework assignment

#include <stdio.h>
#include <stdlib.h>

size_t Strlen(const char *str)
{
const char *p=str;
while(*p) ++p;
return p-str;
}

const char *LongestString( const char (*s1),const char (*s2)) {
size_t l1=Strlen(s1),l 2=Strlen(s2);
return (l1>l2) ? s1 : (l1<l2) ? s2 : NULL;
}

int main(int argc,char **argv)
{
const char *longest;

if(argc!=3) {
fprintf(stderr, "Usage:\n\t %s <string1> <string2>\n",ar gv[0]);
exit(EXIT_FAILU RE);
}

longest=Longest String(argv[1],argv[2]);
if(longest)
printf("The longest string is \"%s\"\n",longe st);
else printf("Both strings are equal length.\n");

return 0;
}
Nov 14 '05 #9
In <cu************ *@zero-based.org> Martin Dickopp <ex************ ****@zero-based.org> writes:
Darklight <ng******@netsc ape.net> writes:
Mail-Copies-To: ng******@netsca pe.net


You set the above header in your posting. This caused my newsreader to
send a mail copy of my reply to you, however it was returned due to an
invalid email address.

Don't set Mail-Copies-To to an invalid email address, please!


Which RFC defines this header?

AFAIK, the right header for this purpose is, and has always been,
Followup-To.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3014
by: David Opstad | last post by:
I have a question about text rendering I'm hoping someone here can answer. Is there a way of doing linguistically correct rendering of Unicode strings in Python? In simple cases like Latin or Japanese I can just print the string and see the correct results. However, I don't know how to get Python to do the right thing for writing systems which require contextual processing. For example, let's say I create this Unicode string in Arabic: ...
0
10727
by: Sarah Tegtmeier | last post by:
Hi I have a question about the correct use of the attribute xsi:schemaLocation. My programm has to process XML files where the value of this attribute causes some problems. The programm is written in C++ using Xerces C++ version 2.3.0. An older older version of the programm used Xerces C++ version 1.6.0. The XML files look like the following example:
1
7756
by: Richard Golebiowski | last post by:
I have been trying to figure this out for quite some time and cannot find any examples in VB.Net or in VB that work correctly. I am working on an application where I want the user to be able to select a peinter and printer tray to print reports out. In Crystal Reports 8.5, I can select a printer and tray and it prints correctly. I did a test report that I use to tell me the value that Crystal Reports is using for the paper source. When I...
14
2151
by: john.burton.email | last post by:
I've done some extensive searching and can't seem to find an answer to this - Is it correct to using "using" with templates, for example: using std::vector; Or do I need to specify the type too: using std::vector<int>; Both seem to "work" on the compiler I have and I can't find any documentation saying which is correct, or are both correct?
6
3479
by: Rob Thorpe | last post by:
Given the code:- r = sscanf (s, "%lf", x); What is the correct output if the string s is simply "-" ? If "-" is considered the beginning of a number, that has been cut-short then the correct output is that r = EOF. If it is taken to be a letter in the stream, then the output should be r = 0, as far as I can see. My compiler gives EOF.
5
2507
by: blackg | last post by:
Input string not in correct format -------------------------------------------------------------------------------- I am trying to view a picture from a table. I am getting this error Input string not in the correct format. Input string was not in a correct format. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it...
2
4978
by: thisis | last post by:
Hi All, I need the PUBS.mdb for pulling images: PUBS.mdb must have the table: pub_info tbl_pub_info : has 3 fields Data_Type : ok Data_Type : ok
0
3160
by: sehguh | last post by:
Hiya Folks, I am Currently using windows xp. Also using Visual Web Developer 2005 and Microsoft Sql server 2005. The main page consists of an aspx page and a master page. The page also consists of a label control(hidden when run in browser). Also an Sql data source control connected to database tables for a photo album. Also label web control ID=UserIdValue. Also a Details View control ID=dvPictureInsert Problem is how to work out...
3
1729
lee123
by: lee123 | last post by:
I have a problem getting the correct to count +1 every time I get an answer right and the incorrect is the same. I have two lbl's named number1 and number2 which produces a Rnd# in each lbl. I have a txt box for the answer called useranswer. A button to check if the answer is right called btnanswer. I have just added two more lbl's for the correct named lblcorrect & the other is lblincorrect. How do I get this to count when the...
10
2197
by: onetruelove | last post by:
I want to creat a post like this blog: http://onlinetoefltest.blogspot.com/2007/08/level-c-lesson-1.html When you chose all the answers and click show answer a msg box will appear and tells how many answers are correct I view the blog source and copied all the code to my post but it didn't work when i click the show answer button in my post. Can any one help me with the code? Thanks in advance
0
8259
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
8358
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8502
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7188
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6119
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5571
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4195
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1805
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1504
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.