简体   繁体   中英

What is the issue in my code? Not getting correct output of C++ program

I'm not getting the correct output of my elab question. Here's the question:

There are faculties in the department, you have to arrange the list of faculties depending upon ID numbers.

TEST CASE 1

INPUT

5 Ram 101 Rahul 95 Ashwin 75 Ahamed 106 Saurav 110

OUTPUT

 After Sorting Name ID Ashwin 75 Rahul 95 Ram 101 Ahamed 106 Saurav 110

Here's the code I implemented using structures:

#include<bits/stdc++.h>
#include<iostream>

using namespace std;

struct faculty{
  string name;
  int id;
};

int main(){
  int n;
  struct faculty arr[n];
  for(int i=0;i<n;i++){
    cin>>arr[i].name;
    cin>>arr[i].id;
  }
  cout<<"After Sorting"<<endl;
  cout<<"Name ID"<<endl;
  
  //insertion sort
  for(int i=1;i<n;i++){
    struct faculty key=arr[i];
    int j=i-1;
    while(j>=0 && arr[j].id>key.id)
    {
      arr[j+1]=arr[j];
      j--;
    }
    arr[j+1]=key;
  }
  
  //printing
  for(int i=0;i<n;i++){
    cout<<arr[i].name<<" "<<arr[i].id;
  }
  return 0;
}

My output:

After Sorting
Name ID
5 0

Can someone help me? I can't figure out what the mistake is.

First, some analysis for your code:

  • Do not ever use #include<bits/stdc++.h> . This is non-compliant C++ code. It will not work with other compilers
  • Do not use using namespace std; . Always prefer using the scope explicitly
  • Always initialize all variables. There should not be any exception
  • Do not use C-style arrays in C++ code. Never. There is no reason for that
  • VLA (Variable length arrays) are non-standard in C++. ( arr[n] )
  • Enable all warnings for your compiler, like with for example -std=c++14 -Wall -Wextra -Wpedantic
  • Use existing containers from the standard library, like std::vector

Concrete errors:

  • You forgot to read n
  • You must replace the VLA by a std::vector
  • You need to add a new line after outputting one record

So, your fixed software would look like this:

#include<iostream>
#include <string>
#include <vector>

struct faculty {
    std::string name;
    int id;
};

int main() {
    int n;
    std::cin >> n;
    std::vector<faculty> arr(n);
    for (int i = 0; i < n; i++) {
        std::cin >> arr[i].name;
        std::cin >> arr[i].id;
    }
    std::cout << "After Sorting" << std::endl;
    std::cout << "Name ID" << std::endl;

    //insertion sort
    for (int i = 1; i < n; i++) {
        faculty key = arr[i];
        int j = i - 1;
        while (j >= 0 && arr[j].id > key.id)
        {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }

    //printing
    for (int i = 0; i < n; i++) {
        std::cout << arr[i].name << " " << arr[i].id << '\n';
    }
    return 0;
}

But this is not the preferred solution.

You should tackle your problem in a different way to come to a better solution.

First, we need to initialize WHAT to do.

  1. We need to address data that consists of "name" and "ID"
  2. Reading this data from a stream, like std::cin must be possible
  3. Outputting the data is necessary
  4. The number of members with name and ID shall be read from the user
  5. All data shall be stored for further evaluation
  6. The number of entries, as specified above, shall be read
  7. Data must be sorted by the ID
  8. The result shall be printed on std::cout

Next, we need to think on HOW we can fullfill the requirements. We do not write any code yet. Ok, lets's see:

  1. For storing that data, we will use a struct, with a std::string for the name and an unsigned int for the ID, because, we assume that the ID will never be negative.
  2. In an object-oriented approach, we keep data and methods operating on that data together. So reading and writing will be defined as a method in a struct. And to save work, we simply overwrite the extractor operator >> . So, we can read the data now from any stream.
  3. For output purposes, we also overwrite the inserter operator << .
  4. We need to read the number of members. We read n, then use an if - statement and check, if that worked.
  5. The number of elements is given by the user and can be anything. So, we need a dynamic container which can grow in size. We will use a std::vector for that.
  6. Now, we must read the specified number of entries. This will call the extractor operator
  7. Sort the data
  8. Show the sorted data on the screen, by outputting all data from vector. This will call the inserter operator.

OK, we clarified the WHAT and the HOW. Now (not before), we can start coding.

Unfortunately, there are millions of possible solutions. I will show a more advanced version, but you can implement anything according to your needs.

Please see the below example:

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

struct Faculty {
    // 1. Our data. Initiliaze with default
    std::string name{};
    unsigned int id{};
    // 2. Define extractor operator for this data
    friend std::istream& operator >> (std::istream& is, Faculty& f) {
        return is >> f.name >> f.id;
    }
    // 3. Define inserter operator for this data
    friend std::ostream& operator << (std::ostream& os, const Faculty& f) {
        return os << f.name << '\t' << f.id;
    }
};

int main() {
    // 4. Get the number of members that we should read, and check, if input worked
    size_t numberOfMembers{};
    if (std::cin >> numberOfMembers) {

        // 5. Here we will store all data
        std::vector<Faculty> data{};

        // 6. Copy all data from std::cin into our data vector
        std::copy_n(std::istream_iterator<Faculty>(std::cin), numberOfMembers, std::back_inserter(data));

        // 7. Sort according to ID
        std::sort(data.begin(), data.end(), [](const Faculty& f1, const Faculty& f2) { return f1.id < f2.id; });

        // 8. Output
        std::copy(data.begin(), data.end(), std::ostream_iterator<Faculty>(std::cout, "\n"));
    }
    return 0;
}

To be compiled with C++14 enabled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM