Home > Back-end >  Alphabetical names
Alphabetical names

Time:10-01

I'm trying to take a collection of names ordered alphabetically then output them How do I Get this to take my output it just stops when I try to repeat the loop and it doesn't seem like my names are being applied to the array

#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
using namespace std;

 
int
main () 
{
  
int i;
  
cout << "How many students:" << endl;
  
cin >> i;
  
 
if (i > 0 && i < 26)
    
    {
      
vector < string > strArray;
      
for (int c = 0; c <= i;   c)
    
    {
      
cout << "Name: ";
      
cin >> strArray[c];
    
} 
sort (strArray.begin (), strArray.end ());
      
cout << strArray[0] << strArray[i];
    
}
  
cout << "<Error wrong class size>";
  
return (0);

}

CodePudding user response:

There are multiple bugs in the shown code.

vector < string > strArray;

This creates a new, completely empty vector.

cin >> strArray[c];

This attempts to read a value from standard input into a value in the vector.

The vector has no values. It is empty. This is undefined behavior, which will result in a crash. Using [] with a vector accesses an existing value in the vector, [] never creates new values in the vector out of thin air.

If your goal is to add values to the vector, then this is what push_back() is for. Alternatively you can resize the array in advance, but that will be slightly inefficient.

Another bug is the flawed for loop:

for (int c = 0; c <= i;   c)
{
      cout << "Name: ";
      cin >> strArray[c];    
}

i is the number of students. Suppose it was 3. The for loop, therefore, will iterate for the values of c of 0, 1, 2, and 3. After all, all of these are <= 3. You might've noticed that this will prompt for four names, instead of 3.

cout << strArray[0] << strArray[i];

This will show the 0th and the ith value in the vector. There will be no intervenient space. If i is three, and the previous bug is correctly fixed, you will have values strArray[0] through strArray[2] in the vector. An attempt to access strArray[3] will be undefined behavior. There is no strArray[3].

If the intent here is to show the entire contents of the vector you will need to implement logic correctly, employing another for loop, correctly.

cout << "<Error wrong class size>";

This message gets printed at the end of main. Whether the right or the wrong class size was initially entered. Showing this message even if the correct class size was entered is obviously wrong.

All of these bugs must be fixed in order for the shown program to produce the intended results. It will be helpful for you to always be mindful of the Golden Rule Of Computer Programming: "Your computer always does exactly what you tell it to do, instead of what you want it to do". Always be mindful of exactly what you're telling your computer to do, in order to avoid these kinds of common bugs.

  •  Tags:  
  • c
  • Related