Arrays

This code is suppose to output:

str1=abcd str2=efg
strlen(str1)=4 strlen(str2)=3
str1=efg
str1=efgefg
strcmp(str1, str2)=101
strcmp(str2, "efh")=-1
str2=hi
str2=hi jkl

but instead i am getting:

str1=abcd str2=efg
strlen(str1)=4 strlen(str2)=3
str1=efg
str1=efgefg
strcmp(str1, str2)=1
strcmp(str2, "efh")=1
str2=hi
str2=hi jkl
was wondering if anyone could help point in me in the direction of my mistake. thanks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
  #include <iostream>

using namespace std;

unsigned int strlen(const char s[])
{
    unsigned int n;

    for (n = 0; s[n]; n++); 

    return n;
}

void strcpy(char t[], const char s[])
{
    for (int i = 0; t[i] = s[i]; i++);
}
void strncpy(char t[], const char s[], const unsigned int n)
{
    unsigned int i;

    for (i = 0; i < n and s[i]; i++)
        t[i] = s[i];
    t[i] = '\0';
}


void strcat(char t[], const char s[])
{
    unsigned int i;

    for (i = 0; t[i]; i++);
    strcpy(t+i, s);
}
int strcmp( const char t[], const char s[])
{
	unsigned int i;
	for( i < 0; t[i] and s[i]; i++){
		if(t[i] != s[i]);
			break;
		return t[i] - s[i];
	}
}
main()
{
	 char str1[20] = "abcd", str2[20] = "efg";

    cout << "str1=" << str1<< " str2=" << str2 << endl;
    cout << "strlen(str1)=" << strlen(str1)<< " strlen(str2)=" << strlen(str2) << endl;

    strcpy(str1, str2);
    cout << "str1=" << str1 << endl;

    strcat(str1, str2);
    cout << "str1=" << str1 << endl;

    cout << "strcmp(str1, str2)=" << strcmp(str1, str2) << endl;
    cout << "strcmp(str2, \"efh\")=" << strcmp(str2, "efh") << endl;

    strncpy(str2, "hi jkl", 2);
    cout << "str2=" << str2 << endl;

    strncpy(str2, "hi jkl", 12);
    cout << "str2=" << str2 << endl;
}
Last edited on
Line 39: Remove the ;

Line 41: You will only reach this statement if t[i] == s[i], therefore the difference will always be zero and you will exit on the first interation if the characters match.

Line 43: What value gets returned if you fall through the loop?

Topic archived. No new replies allowed.