array help, i dont understand anything

Pages: 12
seungueon wrote:
i hate arrays


This link explains arrays:
http://www.cplusplus.com/doc/tutorial/arrays/

Arrays are used to store more than one thing and so they can be accessed easily.

Example:
1
2
3
4
5
6
7
8
9
#include <iostream>

int main()
{
        int array[5] = { 0, 1, 2, 3, 4 };
        std::cout << array[0] << '\n' << array[4] << '\n' << array[2] << '\n';

        return 0;
}

To create arrays of string:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>

int main()
{
        // example
        std::string stringArray[5] =
        { "one", "two", "three", "four", "five" };

        return 0;
}


You need to understand the basics.
Last edited on
Compiled and tested:

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
66
#include <iostream>
#include <string>
#include <cctype>

void input(std::string &);
bool isPalindrome(const std::string &);
void print(const std::string &);

int main()
{
    std::string str;
    char repeat;
    
    do
    {
        input(str);
        print(str);
        
        std::cout << "\nDo you want to continue (y or n): " << std::flush;
        while ( !(std::cin >> repeat) ||
               (repeat != std::tolower(repeat) && repeat != std::tolower(repeat)) )
        {
              std::cin.clear();
              std::cin.ignore(1000000, '\n');
              std::cout << "y or n: " << std::flush;     
        }
        std::cout << '\n';
    }
    while (std::tolower(repeat) != 'n');
    
    return 0;
}

void input(std::string &palindrome)
{
	std::cout << "Enter a word and this will check if it is a palindrome or not: ";
	
	std::cin >> palindrome;
}

bool isPalindrome(const std::string &s)
{
	std::string::size_type x = s.size() - 1;
	std::string::size_type mid = s.size() / 2 + 1;
	
	for(std::string::size_type ix = 0; ix != mid; ++ix, --x)
	{
		if (s[ix] != s[x]) { return false; }
	}
	
	return true;
}

void print(const std::string &str)
{
    if (isPalindrome(str))
    {
        std::cout << "\nThe string " << str << " is a palindrome.\n";
    }
    else
    {
        std::cout << "\nThe string " << str << " is not a palindrome.\n";
        std::cout << "The first character is " << str[0] << ".\n";
        std::cout << "The last character is " << str[str.size() - 1] << ".\n";
    }
}
Last edited on
Topic archived. No new replies allowed.
Pages: 12