C++ list with array of strings - c++

I have to make a list with people and their exam result in C++. My problem is that I don't know how to input the array.
I was trying to make 3D array of strings, but it doesn't works. It must be in function! If you have a better suggestions, I will be very grateful
My input must be something like:
Peter Evens 4.86
*other people**
*average result of the group**
*the one with the heighest grade**
*the one with lowest grade**
This is what I have done for now:
#include <iostream>
#define MAXN 200
#define MAXM 200
#define MAXX 200
using namespace std;
void input(char list[][MAXN][MAXM], int n) {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
for (int p = 0; p < n; p++)
cin >> list[i][j][p];
}
}
int main() {
char list[31][MAXN][MAXM];
int n;
cin >> n;
input(list, n);
return 0;
}

You don't need to run the third iteration since you don't have to store the input character by character. The third dimension can be used for storing the entire string.
Try the following way. Observe the corrections i have made in your snippet.
#include <iostream>
#define MAXN 200
#define MAXM 200
#define MAXX 200
using namespace std;
void input(char list[][3][MAXM], int n) {
for (int i = 0; i < n; i++) //number of entries
for (int j = 0; j < 3; j++) { //3 fields - fname, lname and marks
cin >> list[i][j];
}
}
int main() {
char list[31][3][MAXM];
int n;
cin >> n;
input(list, n);
return 0;
}

You must use a vector of struct.
Define your struct this way:
typedef struct details{
string Fname;
string Lname;
float marks;
} details;
And vector should look like
vector< details > info;
I am just showing you how to implement this in the following code:
void insertValues(vector< details >& info){
int n;
details d;
cout<<"Enter the size of record: ";
cin>>n;
cout<<"Enter records: "<<endl;
for(int i=0;i<n;i++){
cin>>d.Fname>>d.Lname>>d.marks;
info.push_back(d);
}
}
void LowestScorer(vector< details > info){
details d;
vector< details >::iterator it=info.begin();
d=*it;
for(;it!=info.end();it++){
if(d.marks > it->marks){
d=*it;
}
}
cout<<"Lowest Scorer: "<<d.Fname<<" "<<d.Lname<<" "<<d.marks<<endl;
}
main should look like this:
int main(){
vector< details > info;
insertValues(info);
LowestScorer(info);
return 0;
}

As mentioned in above comments, it's good time to learn vector. It's very easy. Below is a very simple and neat solution:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
typedef vector<pair<string, string> > Container;
int main()
{
Container container;
container.push_back(make_pair("Peter Evens", "4.86"));
container.push_back(make_pair("Other name", "his score"));
return 0;
}

Related

How to copy char array of a structure into another char array of a structure?

#include <iostream>
using namespace std;
struct stud
{
char name[10];
int id;
};
int input(stud a[], int size)
{
for(int i=1; i<=size; i++)
{
cout<<"name = ";
cin>>a[i].name;
cout<<"id = ";
cin>>a[i].id;
}
cout<<endl;
return 0;
}
int output(stud a[], int size)
{
for(int i=1; i<=size; i++)
{
cout<<"name = "<<a[i].name<<" ";
cout<<"id = "<<a[i].id<<" ";
}
cout<<endl;
return 0;
}
int copy(stud a[], stud x[], int size)
{
for(int i=1; i<=size; i++)
{
x[i].name=a[i].name;
x[i].id=a[i].id;
}
output(x,size);
cout<<endl;
return 0;
}
int main()
{
struct stud s[3], x[3];
input(s,3);
output(s,3);
copy(s,x,3);
return 0;
}
In this program the statement in function copy x[i].name =a[i].name; is not copying contents from 1 structure object to another. I have tried to put this statement in for loop for(int j=1;j<=10;j++) x[i].name[j] =a[i].name[j]; but still not working.
please suggest what should be changed or some alternatives for this.
i'll be very thankful to you for this.
regards,
umar
Either using a loop to copy each character in the name field or using thestrcpy function from <cstring> header works.
int copy(stud a[], stud x[], int size) {
for(int i = 1; i <= size; i++) {
// for(unsigned j = 0; j < 10; j++) {
// x[i].name[j] = a[i].name[j];
// }
strcpy(x[i].name, a[i].name);
x[i].id = a[i].id;
}
output(x, size);
cout << endl;
return 0;
}
But since you tagged this as c++, consider using std::string instead of a char array, unless you have a particular reason for using a char array. In that case x[i].name = a[i].name would have worked just fine and you could also use the standard algorithm library for copy. Also, using std::array instead of a raw C array for you "array of structures" might be a better option (does not degenerate into a pointer like a regular C array does).
Evrey single one of your loops is wrong, because in C++ arrays start at zero. So not
for(int i=1; i<=size; i++)
instead
for(int i=0; i<size; i++)
You cannot copy arrays by writing a = b;. Since your arrays are really strings there's a built in function strcpy to copy strings.
strcpy(x[i].name, a[i].name);
If you use = to copy struct, the char array inside that struct will be copied. You don't need to do anything more.
#include <iostream>
using namespace std;
typedef struct{
char name[10];
} type_t;
int main() {
type_t a = {"hihi"};
type_t b;
b = a;
a.name[0] = 'a';
cout<<a.name<<endl;
cout<<b.name<<endl;
return 0;
}
output:
aihi
hihi
ideone: https://ideone.com/Zk5YFd

Vector sorting using BUbble sort C++

I need a simple program to accept string vector and sort using bubble sort and display the result. While executing the program automatically terminates.
#include<bits/stdc++.h>
#include<iostream>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
vector<string> v2;
void Bsortchar(vector <string> &ch)
{
int i, j;
string temp[1][200];
int charLength = ch.size();
cout<<ch.size();
for(i = 0; i <= charLength; i++)
{
for (j=0; j < (charLength -1); j++)
{
if (ch[j+1] < ch[j])
{
temp[1][200] = ch[j];
ch[j] = ch[j+1];
ch[j+1]= temp[1][200];
}
}
}
return;
}
int main()
{
int charSize;
//**********************************************************
cout<<"Enter the Size of the char Vector"<<endl;
cin>>charSize;
cout<<"Enter the char Vector"<<endl;
string c;
for(int i=0;i<=charSize;i++)
{
cout<<i<<":";
getline(cin,c);
v2.push_back(c);
}
//************************************************************
Bsortchar(v2);
//***********************************************************
cout<<endl<<"The sorted character vector array is : "<<endl;
for(int i=0;i<=charSize;i++)
{
cout<<v2[i]<<" ";
}
//***********************************************************
return 0;
}
Need to accept string from the user and display the results after performing a bubble sort.
You have undefined behaviour temp[1][200] is off the ends of both parts of this (gratuitous) 2d array.
You don't need an array here, just a single temporary.
auto temp = ch[j];
ch[j] = ch[j+1];
ch[j+1]= temp;
Or, preferably, you can use an existing function
std::swap(ch[j], ch[j+i]);

C++ determinable array input in one line

I'm pretty new to c++ and can't seem to find correct way to code this. I have array of n digits, my code now:
int main()
{
int n,i;
cin >> n;
int a[n];
for (i=1;i<=n;i++)
{
cin >> a[i];
}
return 0;
}
This way every element of array has to be input in different line, is it possible to put all elements of a array in one line, with space between them.
I am assuming your question is "what is the correct way to do this?"
I would do it this way:
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
int main()
{
int n;
cin >> n;
vector<int> v;
int i = 0;
int value;
while (i++ < n && cin >> value)
{
v.push_back(value);
}
char const* sep = "";
for (auto item : v)
{
cout << sep << item;
sep = " ";
}
cout << endl;
}
Note that this code is making assumptions that the input is well formed. If you need something that is more robust in handling possibly malicious input, that would require extra effort. This code, as given, will give-up-trying-and-continue which may or may not be suitable for your purposes.
The following code snippet of your program is a Variable Length Array(VLA) and this is only supported in C since ISO C99.
cin >> n;
int a[n];
And as previously pointed out, you can also use std::vector instead.
int main()
{
int size;
std::cin >> size;
int *array = new int[size];
delete [] array;
return 0;
}
References:
http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
How to create a dynamic array of integers
Without using stl container , one can implement like so:
#include <iostream>
#include <string>
#include "stdlib.h"
void GetInput(int* inputs, int n)
{
// store the entered numbers in a char[]
std::string word;
std::cout << "enter numbers (separate by space) ";
std::getline(std::cin, word);
char ch[100];
strcpy_s(ch, word.c_str());
char *temp = ch;
// parse the char[] for integers
for (int i = 0; strcmpi(temp, "") != 0 && i <= n; temp++,i++) {
*(inputs +i) = std::strtol(temp, &temp, 10);
}
}
int main()
{
int n = 3;
int inputs[10];
GetInput(inputs,n);
for (int j = 0; j < n; j++)
std::cout << inputs[j] << " \n";
return 0;
}
Output:

I can not enter the data for arrays

I want to enter n times values for c and e arrays. The following program doesn't allow me to even enter the value of 'n'. Could you tell me where is the mistake?
#include <iostream>
using namespace std;
int main()
{
int n,c[n],e[n];
cin>>n;
for(int i=0;i<n;i++){
cin>>c[i]>>e[i];
}
return 0;
}
"n" should be defined before using it to fix array size. Also, const int or constant should be used to declare array size not plain int.
In order to use plain datatype, you can initialize array dynamically like
vector<int> a(n); or
int a = new int[n]
int n,c[n],e[n];
This declaration creates arrays c and e on stack with random size, because n as an automatic variable is initialized with random value. Instead you need to dynamically create arrays on heap or use std::vector.
Example:
#include <iostream>
#include <vector>
using namespace std;
int main() {
// your code goes here
int n;
vector<int> v;
std::cin >> n;
v.resize( n);
for( int i = 0; i < n; ++i) {
cin >> v[i];
}
for( int i = 0; i < n; ++i) {
cout << v[i];
}
return 0;
}
http://ideone.com/QhgfNv
In the line of
int n,c[n],e[n];
Computer don't know the exact value of 'n', so it can't alloc memory of array.
The simplest solution is create array with fixed number, and check n after you know the value of n as follows:
int n, c[1024], e[1024];
cin >> n;
if (n > 1024) { /* error */ }
The other way is malloc memory after u know the value of n:
int n;
cin >> n;
int *c = new int[n];
int *e = new int[n];
xxxx
delete [] c;
delete [] e;
You can try something like this:
#include <iostream>
using namespace std;
int main()
{
int temp = 100; /*Random value*/
int c[temp];
int e[temp];
int n;
cin>>n;
for(int i=0;i<n;i++){
cin>>c[i]>>e[i];
}
return 0;
}
Now, I chose temp as 100, but you can do big as your int can store. Now, if n is lower than temp, your for cycle will let you save your values without troubles.

Filling 2-D arrays from user input

I have a bit of a problem, I am writing a program to ask the user to enter numbers for a Sudoku grid, and then store them in a 2-d array. I know how to print out the array to show the Sudoku grid, But I am having trouble getting the array elements set to the numbers that the user enters, can anyone help?
This is all that I have, which I know is not much but I have only ever done this with 1-d arrays before.
Code:
#include <iostream>
using namespace std;
void fillGrid1(int grid1, int sizeOfArray) {
for(int x = 0; x < sizeOfArray; x++) {
grid1[x][9] = x;
}
}
int main()
{
int grid1[9][9];
fillGrid1(grid1, 9);
for(int row = 0; row < 9; row++) {
for(int column = 0; column < 9; column++) {
cout << grid1[row][column] << " ";
}
cout << endl;
}
}
Here you have two functions, one to interactively fill the hole sudoku by getting the user input. The other for printing the sudoku. With the little information you gave it's what I think you seek:
#include <iostream>
#include <stdio.h>
#include<stdlib.h>
using namespace std;
void interactiveSudokuFill(int grid1[9][9]){
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
string theString;
cout<<"Write the value to prace in Sudoku["<<y<<"]["<<x<<"] :"<<endl;
std::getline(cin,theString);
int nr=atoi(theString.c_str());
grid1[y][x]=nr;
}
}
}
void printSudoku(int grid[9][9]){
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
cout<<"["<<grid[y][x]<<"]";
}
cout<<endl;
}
}
int main()
{
int grid1[9][9];
interactiveSudokuFill(grid1);
printSudoku(grid1);
}
There are other more safe/elegant ways of doing this(for example user input should have been checked before delievering it to atoi()), but this way is the simpler I can think of.
Firstly, you're taking in an int where you expect an array:
void fillGrid1(int grid1, int sizeOfArray)
// ^^^^^^^^^
This should be something of the form,
void fillGrid1(int grid1[9][9], int sizeOfArray)
Next is that you should use a nested loop to access the elements of the multidimensional array:
void fillGrid1(int grid1[9][9], int sizeOfArray)
{
for (int i = 0; i < sizeOfArray; ++i)
{
for (int k = 0; k < sizeOfArray; ++k)
{
grid1[i][k] = x; // shouldn't x be the number the user entered?
}
}
}
You should also zero-fill your array:
int grid1[9][9] = {0};