#### Archived

This topic is now archived and is closed to further replies.

# two questions: on lists and strncmp

This topic is 5334 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

hello, i have two questions here. please keep in mind that i''m don''t have much experience in programming. ok first, say that you have dates, ie 03/15/2004 and 03/04/2004. say that i need to compare these two dates (first year, then month, and then the day, depending on if they''re equal or not). So i''m thinking of using strncmp but i''m not sure how i''d use it. if anyone could show me how this could be implemented, that''d be great. second, say that there is a list declared, i.e. list<things> available; available would represent say, all the candies i have available. but for debugging purposes, i need to cout everything available that i have. how would i do that with a list? any help is appreciated!

##### Share on other sites
please be aware that strcmp and strncmp are different: the one without the n (str cmp), compare the whole strings. The second one (str n cmp) compares the 2 strings UP TO the number of letters specified.

All string cmp functions return:
negative number - first string less than second
0 - strings are equal
positive number - first string greater than second

so for instance if you had strings a = "marry" b = "marraige"

strcmp(a, b) // would return (>0), because the a is lower than y
strncmp(a, b, 4) // would return 0 because the first 4 characters match

for your dates: a = "03/15/2004" b = "03/04/2004"

strcmp(a, b) // returns (>0), cause the 1 in 15 is greater than the 0 in 04.

HOWEVER, you CANNOT use this to figure out which date is later in a single date - cause your date is note in proper order (you are using MM/DD/YYYY, notice that the day have the least significance, but is in the middle - therefore making it impossible to compare dates in this format using just 1 single string compare).

The easiest way to output the contents of a list are just to write the loop:

cout << "Outputing Available:" << endl;
for(iterator it = available.begin(); it != available.end(); ++it)
cout << ''\t'' << *it << endl;

Other ways are nice once you know how, like writing a simple functor and passing it to the for_each function ... but that''s a little more advanced.

##### Share on other sites
Those sound like homework questions.

Hint: for the first one, forget string compares, and look into sscanf....

1. 1
Rutin
43
2. 2
3. 3
4. 4
5. 5

• 9
• 27
• 20
• 9
• 20
• ### Forum Statistics

• Total Topics
633398
• Total Posts
3011659
• ### Who's Online (See full list)

There are no registered users currently online

×