store variable and print-out

I am brand new to c++. I want to store variable and print out them

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
#include<iostream>
using namespace std;
int main()
{
	float store[2];
	int i;
	int mynum;
	int step;
	int temp;
	std::string title;
	
	cout << "Enter the number of elements to be stored: ";
	cin >> mynum;
	
	for(int i=0;i<mynum;++i)
	{
	 cout << "Enter one element: ";
	 cin >> store[i];
	 cin.ignore();
	 cout << "Enter your title: ";
	 getline(cin,title);
    }
	
	for(step=0; step<mynum-1; ++step)
	{
	 for(i=0; i<mynum-step-1;++i)
	 {
	 	if(store[i]>store[i+1])
	 	{
	 		temp=store[i];
	 		store[i]=store[i+1];
	 		store[i+1]=temp;
		 }
	 }
    }
    
     for(i=0;i<mynum;++i)
     {
       cout << "IN ASCENDING ORDER: ";
       cout << store[i] << " ";
       cout << "SHOW TITLE: ";
       cout << title;
       cout << endl;
     }
    return 0;
}


In "SHOW TITLE" section, I only can show title2
how can I show title1 also??
1
2
3
4
5
6
7
Enter the number of elements to be stored: 2
Enter one element: 3.4
Enter your title: test1
Enter one element: 5.6
Enter your title: test2
IN ASCENDING ORDER: 3.4 SHOW TITLE: test2
IN ASCENDING ORDER: 5.6 SHOW TITLE: test2

Last edited on
1
2
3
4
5
6
7
8
 for(i=0;i<mynum;++i)
     {
       cout << "IN ASCENDING ORDER: ";
       cout << store[i] << " ";
       cout << "SHOW TITLE: ";
       cout << title; // This prints the last thing the user has input for the title
       cout << endl;
     }


You can do something similar to what you did with your elements, which is storing it into an array that holds strings. Note: You should probably change the initialization of the array with a const variable.
1
2
3
const int size = 2;
std::string listOfTitles[size];
float store[size];


Just change your
getline(cin, title);
and remember to do the swap for the titles also if the swap occurs in your nested loop.
Topic archived. No new replies allowed.