Vector & Array

I am wanting to make a list of names and other information. Then print them all out at the end. I am working with this code but can't seem to manipulate it the right name.

What I am looking to do is something like...

Add(A) for adding information or List(L) for listing all the input.

Enter Name: (get the input)
Enter Place of birth: (get the input)
Year of birth: (get the input)

and repeat until I say for it to. So I can input A, and then do it again. Once I decide that I have put enough information in, I want to press, L...and list all the people's information.

So I think I need an array and vector...but I could be wrong.

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
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<double> student_marks;
    double mark;
    char answer;
    
    cout << "Enter marks (y/n)? " << flush;
    cin >> answer;
    
    while (answer == 'y' || answer == 'Y')
    {
        cout << "Enter value: " << flush;
        cin >> mark;
        
        student_marks.push_back (mark);
        
        cout << "More students (y/n)? " << flush;
        cin >> answer;
    }
    

    
    return 0;
}
What you have is OK - vectors are better than arrays. Here's a slight modification. Now what you have to consider is the data structure of what you are planning to store. A class or struct is ideal. Your (single) vector would store Student objects rather than just marks alone. ( vector<Student> not just vector<double> )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<double> student_marks;
    double mark;
    char answer;
    
    while (cout << "More students (y/n)? " && cin >> answer && std::toupper(answer) == 'Y' )
    {
        cout << "Enter value: ";
        cin >> mark;
        
        student_marks.push_back (mark);
    }
 
    return 0;
}




Vectors within vectors even:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>
#include <vector>

struct Student
{
    std::string name;
    std::string place_of_birth;
    int year_of_birth;
    std::vector<double> marks;
};


int main()
{
    std::vector<Student> student_marks;
    
    // blah blah
    
    return 0;
}

Last edited on
Ok that didn't answer anything or help.
You don't need to flush cout before reading from cin. The two streams are tied, so this is done automatically:
https://en.cppreference.com/w/cpp/io/basic_ios/tie
I am not sure how that helps. I want to take different inputs...and print them.

Enter name: bob
enter place of birth: dallas, tx
enter year of birth: 1985

another name? : Yes

Enter name: jo
enter place of birth: leavenworth, wa
enter year of birth: 2011

another name? : no

You entered:

Enter name: bob
enter place of birth: dallas, tx
enter year of birth: 1985

Enter name: jo
enter place of birth: leavenworth, wa
enter year of birth: 2011

Hello jax16,

Consider this to get you started:
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
#include <cctype>  // <--- Added.
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<double> student_marks;
    double mark;
    char answer;

    cout << "\n Enter marks (only good for 1 student.)? \n";  // <--- Changed.
    //cin >> answer;

    std::cout << '\n';
    
    //while (std::tolower(answer) == 'y')
    //{
    //    cout << "\nEnter value: ";
    //    cin >> mark;

    //    student_marks.push_back(mark);

    //    cout << "More marks (y/n)? ";  // <--- Changed.
    //    cin >> answer;
    //}

    while (cout << " Enter value (-9 to quit): " && cin >> mark && mark != -9)
    {
        student_marks.push_back(mark);
    }

    std::cout << "\n ";

    for (size_t idx = 0; idx < student_marks.size(); idx++)
    {
        std::cout << student_marks[idx] << (idx < student_marks.size() - 1 ? ", " : "\n");
    }

    return 0;  // <--- Not required, but makes a good break point.
}


You could use parallel vectors for each piece of information, but the struct would be a better choice and not that hard to change the above code to deal with it.

It looks like you would want to start with a menu to "add" or "list", do what you need and return to the menu to either add more or list what you have.

You would also need a loop for "main", I am thinking a do/while loop to keep repeating until you choose to quit the program.

Andy
An array is a very simple, low level thing. It is little more than a fixed-sized block of memory -- you can't assign/copy/resize/more to them. Most programmers would say to use a vector and keep arrays out of your code most of the time. A vector is an object/type that is a 'better array' really. It can do those things I said and more -- resize, assign, copy, etc are all trivial because the class hides the loops and low level details.

If you can use structs/classes, the right thing to do is to make a vector of those, which is what againtry tried to say.
If you cannot yet use those, you need another approach -- parallel arrays is mentioned.

at a KISS level:
int x[10];
vector<int> x(10);
will do the same thing. x can do MORE, but right off the bat vec x is pretty much an array with 10 locations and ready to do anything array x could.

I didnt say anything new here, just trying to condense the points above so you can understand what you were told. If it isnt helping, say why -- not sure what you know and do or do not understand...
Last edited on
Ok, what about this? Now I am running into this issue...when I first run it, it kind of smudges it together. And I don't want a set number. I want as many as I want until I say list. So not just a set number of 3 like I currently have.


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
67
68
69
70
71
72
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

struct people_t {
    string name, place;
    int year;
} group [3];

void printpeople (people_t people);

int main ()
{
    string mystr;
    int n;
    char choice;
    
    while (1)
    {
        cout << "Add(A), List(L) or Quit(Q) : ";
        cin >> choice;
        switch (choice)
        {
            case 'A':
            {
    
    for (n=0; n<3; n++)
    {
        cout << "Enter Name: ";
        getline (cin,group[n].name);
        cout<<"State of Birth: ";
        getline (cin, group[n].place);
        cout << "Enter year: ";
        getline (cin,mystr);
        stringstream(mystr) >> group[n].year;
    }
                break;
            }
                
                
                case 'L':
            {
                for (n=0; n<3; n++)
                {
    cout << "\nYou have entered these movies:\n";
    for (n=0; n<3; n++)
        printpeople (group[n]);
                }
                break;
            }
            case 'Q':
                
            {
                cout << "Be Blessed! Bye!";
               return 0;
            }
                
        }
    }
}
void printpeople (people_t people)
{
    cout<<"Name: "<<people.name<<endl;
    cout<<"State of birth: "<<people.place<<endl;
    cout<<"Year of birth: "<<people.year<<endl;
}



Why do you have the array as global variable? There is no need for that.

Please, try to have more intuitive indentation. It helps to see scopes.

Add just one person at a time.

You can have an array that has more elements than what you use:
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
struct people_t {
    string name, place;
    int year;
};

void printpeople (people_t people);

int main ()
{
  constexpr int N = 100;
  people_t    group[N];
  int n = 0;
  while (true) {
    cout << "Add(A), List(L) or Quit(Q) : ";
    char choice {};
    cin >> choice;
    switch (choice) {
      case 'A':
        if ( n < N ) {
          cout << "Enter Name: ";
          getline (cin,group[n].name);
          cout<<"State of Birth: ";
          getline (cin, group[n].place);
          cout << "Enter year: ";
          string mystr;
          getline (cin,mystr);
          stringstream(mystr) >> group[n].year;
          ++n;
        } else {
          cout << "Array is already full\n";
        }
        break;
      case 'L':
Hello jax16,

Consider this:
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <cctype>  // <--- For "std::tolower() and std::toupper()" + others.
#include <iostream>
#include <limits>
#include <string>
#include <vector>

using namespace std;

struct People_t
{
    string name, birthState;
    int year{};
};

void Add(std::vector< People_t>& peopleInfo);
void printpeople(std::vector<People_t>& peopleInfo);

int main()
{
    char choice{};
    std::vector< People_t> peopleInfo;

    do
    {
        cout << "\n Add(A), List(L) or Quit(Q) : ";
        cin >> choice;

        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.

        choice = std::toupper(choice);

        switch (choice)
        {
            case 'A':
                Add(peopleInfo);
                break;

            case 'L':
                printpeople(peopleInfo);
                break;
            case 'Q':
                cout << "Be Blessed! Bye!";
                break;

        }
    } while (choice != 'Q');

    return 0;  // <--- Not required, but makes a good break point.
}

void printpeople(std::vector<People_t>& peopleInfo)
{
    for (int idx = 0; idx < 3; idx++)
    {
        cout
            << "\nName: " << peopleInfo[idx].name << '\n'
            << "State of birth: " << peopleInfo[idx].birthState << '\n'
            << "Year of birth: " << peopleInfo[idx].year << '\n';
    }

        //cout << "\nYou have entered these movies:\n";  // <--- What does this have to do with the program??
}

void Add(std::vector< People_t>& peopleInfo)
{
    People_t temp;

    do
    {
        cout << "\n Enter Name (Q to quit): ";
        getline(cin, temp.name);

        if (std::toupper(temp.name[0]) == 'Q')
            break;  // <--- Or you could use "return".

        cout << "State of Birth: ";
        getline(cin, temp.birthState);

        cout << "Enter year: ";
        std::cin >> temp.year;

        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.

        peopleInfo.emplace_back(temp);
    } while (true);
}


Andy
There's issues around Add. What if the entered name starts with Q?

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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <cctype>
#include <iostream>
#include <limits>
#include <string>
#include <vector>

struct Person
{
	std::string name;
	std::string birthState;
	int year {};
};

using People = std::vector<Person>;

std::istream& cignore()
{
	return std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

std::ostream& operator<<(std::ostream& os, const Person& per)
{
	return (os << "\nName: " << per.name
		<< "\nState of birth: " << per.birthState
		<< "\nYear of birth: " << per.year);
}

void Add(People& peopleInfo);
void printpeople(const People& peopleInfo);

int main()
{
	char choice {};
	People peopleInfo;

	do
	{
		std::cout << "\nAdd(A), List(L) or Quit(Q): ";
		std::cin >> choice;
		cignore();

		choice = std::toupper(choice);

		switch (choice)
		{
			case 'A':
				Add(peopleInfo);
				break;

			case 'L':
				printpeople(peopleInfo);
				break;

			case 'Q':
				std::cout << "Be Blessed! Bye!";
				break;

			default:
				std::cout << "Invalid choice\n";
				break;

		}
	} while (choice != 'Q');
}

void printpeople(const People& peopleInfo)
{
	for (const auto& p : peopleInfo)
		std::cout << p << '\n';
}

void Add(People& peopleInfo)
{
	Person temp;

	while ((std::cout << "\nEnter Name (Q or <CR> to quit): ") && std::getline(std::cin, temp.name) && !temp.name.empty() && !(temp.name.size() == 1 && std::toupper(temp.name[0]) == 'Q')) {
		std::cout << "State of Birth: ";
		std::getline(std::cin, temp.birthState);

		while ((std::cout << "Enter year: ") && !(std::cin >> temp.year)) {
			std::cout << "Invalid year\n";
			std::cin.clear();
			cignore();
		}

		cignore();

		peopleInfo.emplace_back(temp);
	}
}

Thank yall, this helps
Topic archived. No new replies allowed.