Click here to Skip to main content
15,918,333 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
For example.
If I typed the name Bob Marley. The program will work.
But if I type the name like this Marley, Bob. The program crashes.

What I have tried:

This is the program that I have made.


#include <iostream>
#include <string>

using namespace std;

int main()
{
 string name[20];
 int grade[20];
 int index[20];
 int i, j;

 for(i=0;i<=20;i++)
 {
  cout << "Please enter name: ";
  cin >> name[i];
  cout << "Please enter grade: ";
  cin >> grade[i];
 }

 for(i=0;i<=20;i++)
 {
  index[i]=i;
 }

 for(i=0;i<=20;i++)
 {
  for(j=i+1;j<=20;j++)
  {
   int temp;
   
   if(name[index[i]] > name[index[j]])
   {
    temp = index[i];
    index[i] = index[j];
    index[j] = temp;
   }
  }
 }
 cout << endl;

 for(i=0;i<=20;i++)
 { 
  cout << name[index[i]] << "        "
   << grade[index[i]] << endl;
 }

 cin.ignore();
 cin.get();

 
}
Posted
Updated 10-Mar-17 22:04pm

C++
string name[20];

This is not an array of 20 strings, this is a string of size 20.


When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 
v2
Comments
Richard MacCutchan 11-Mar-17 4:07am    
No, it's an array of strings.
Patrice T 11-Mar-17 10:25am    
oops, my bad.
Jochen Arndt 11-Mar-17 4:09am    
"This is not an array of 20 strings, this is a string of size 20."

In C/C++ type var[]; defines an array.
Patrice T 11-Mar-17 10:26am    
oops, my bad.
You have arrays with sizes of 20. But in all your loops you are iterating over 21 items:
for(i=0;i<=20;i++)

With the last iteration you are accessing the item array[20] but allowed indexes are from 0 to 19. This is called out of bound access. What happens can't be predicted. While reading just returns wrong values, writing will overwrite other data and may result in an access violation.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900