Vector_Exercise - Program exits - c++

I am trying to solve a problem which is like, if you enter a name: Eve which have three letters, so the program will eliminate the suitor of the multiple of that letter. If the multiple exceeds the size of the vector, then it will return back from the first index and so on. Did a cin for string because I just need the first name.
The program exits after the input. Tried to comment the last for loop and it worked fine, but that's the main part. Appreciate help, thanks in advance.
#include<iostream>
#include<vector>
#include<stdlib.h>
using namespace std;
int main()
{
int nos,n; string name;
cout<<"Enter Number of Suitors: "<<endl;
cin>>nos;
cout<<"Enter Your First Name: "<<endl;
cin>>name;
n=name.size();
vector<int>suit(nos);
for(int i=0;i<nos;i++)
suit[i] = i+1;
for(int i=0;i<nos;i++)
cout<<suit[i]<<" ";
for(n=n-1;(suit.size()!=1);n+=n)
{
n = n%nos;
suit.erase(suit.begin(),suit.begin()+n);
}
cout<<suit.front();
system("pause");
return 0;
}//close main

Related

Program exits before executing rest of the program

I am trying to create a students program but it stops after I put the 4th name, it doesn't allow me to put the grades neither shows the list at the end...
#include<iostream>
using namespace std;
int main()
{
string name[4];
double g1[4],g2[4],avg[4];
int cont;
for(cont=1;cont<=4;cont++)
{
cout<<"STUDENT "<<cont<<"\n";
cout<<"Name: ";
cin>>name[cont];
cout<<"First Grade: ";
cin>>g1[cont];
cout<<"Second Grade: ";
cin>>g2[cont];
avg[cont]=(g1[cont]+g2[cont])/2;
}
cout<<"STUDENTS LIST"<<"\n";
cout<<"--------------"<<"\n";
for(cont=1;cont<=4;cont++)
{
cout<<name[cont]<<" "<<avg[cont]<<"\n";
}
}
string name[4]; is an array with 4 elements. Valid indices are 0,1,2 and 3. Your loops skips the first element and accesses the array out-of-bounds on the last iteraton. That causes undefined behavior. Anything could happen.
The two loops for(cont=1;cont<=4;cont++) is wrong because you can only use indice 0, 1, 2, 3 for 4-element arrays.
You should use for(cont=0;cont<4;cont++) instead and change cout<<"STUDENT "<<cont<<"\n"; to cout<<"STUDENT "<<(cont+1)<<"\n";.
Another option is to add one more elements to each arrays. First elements of the arrays won't be used then, but this may contribute for readability for you.

How to debug my C++ program that calculates CGPA?

I have been trying to write a simple code in C++ to calculate CGPA. It is a practice code. There is no error in code when I start to build. But it is not running.
I am using codeblocks. I have checked everything. but can not find any problems in it.
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int g,h,i,a=0, grade[g],hour[h];
char course[10];
float z=0,sum =0, result=0, totalhour=0;
cout<<"How Many Course's do you want to calculate for CGPA: ";
cin>> a;
cout<<endl;
cout<<"Please Enter your Course name, Credit hour & Grade point of the your course"<<endl;
for(i=1;i<=a;i++)
{
cout<<i<<". no Course name: ";
cin>>course[i];
cout<<"-----";
cout<<"Credit Hour: ";
cin>>hour[h];
cout<<"-----";
cout<<"Grade point: ";
cin>>grade[g];
cout<<"\n";
}
for (i=1; i<=a;i++)
{
cout<<i<<".no Course----";
z= grade[g]*hour[h];
cout<<"Grade point X Credit Hour = "<<grade[g]<<" X "<<hour[h]<<" = "<<z<<endl;
sum = sum+z;
totalhour= totalhour+hour[h];
}
result = sum / totalhour;
cout<<"Your total Credit hour Completed is : "<<totalhour<<endl;
cout<<"----Your Total CGPA is -------- = "<<result<<endl;
getch();
return 0;
}
You have some problems in your code:
What happens if user input is larger then 10? you assume it will be smaller (you will get undefined behavior since the array size is 10, and your for loop runs until user input)
int g,h,i,a=0, grade[g],hour[h]; - what is the size of grade and hour? you can not "dynamically" give them a size. You must tell what size they are when you declare them, unless you use dynamic containers such as std::vector.

C++ Character array element based on index no comparison

I'm attempting a logical comparison at an element in a char-array based on index number but my compiler says illegal comparison. Any ideas about what's going on?
#include <iostream>
#include <cstring>
#include <iomanip>
#include <fstream>
using namespace std;
ofstream MyFile("Assignmentfile.txt");
int userno;
char name[16];
char lastname[16];
char address[51];
char cellno[14];
char landlineno[12];
int sent;
void userinput();
void searchfunc();
void deletecontact();
void displaycontact();
void modifycontact();
void sortcontact();
void findcontact();
int main()
{
MyFile<<"First Name Last Name Address Cell Number Landline Number"<<endl;
userinput();
return 0;
}
void userinput()
{
{
cout<<"Would you like to enter a new contact? (1/0) ";
cin>>sent;
while (sent==1)
{
cout<<"Enter Name: ";
cin>>name;
MyFile<<left<<setw(16)<<name<<"|";
cout<<"Enter Last name: ";
cin>>lastname;
MyFile<<left<<setw(16)<<lastname<<"|";
cout<<"Enter Address: ";
cin>>address;
MyFile<<left<<setw(51)<<address<<"|";
cout<<"Enter Cell Number: ";
cin>>cellno;
if (cellno[0]=="+")
{
cout<<"Enter Cell number again starting with +92"; // The problem appears here //
}
MyFile<<left<<setw(14)<<cellno<<"|";
cout<<"Enter Landline Number: ";
cin>>landlineno;
MyFile<<left<<setw(12)<<landlineno<<endl;
cout<<endl;
cout<<"Would you like to enter a new contact? (1/0) ";
cin>>sent;
}
MyFile.close();
}
}
The program must be able to write and read from a text file. It can create contacts, modify them, delete them, sort them and search through them. The problem is that the cell number must start from "+92" i.e "+923454356568". I thought that if (cellno[0]=="+") and so on would work.
I cannot use strings and only have to rely on character type arrays. Using strings would make all of this a piece of cake.
Below is the assignment I wish to complete.
Your problem is this line:
if (cellno[0]=="+")
You are comparing single character, at index 0 in cellno char array (which hopefully contains a C string) with string literal, which is a pointer (as your compler error says).
You want to compare a single char, like this:
if (cellno[0]=='+')
Note how single and double quotes have a very different meaning!
You code has a lot of other issues, too many to list here, but that should solve the problem you are asking about. But one advice I add: do not use C strings in C++, if you can avoid it! Use std::string as soon as you are allowed to!

Exiting Loop using Enter(Return Key) C++

First of all thanks for answering and helping out...
Now i was making a program to let the user enter any number... and then use the program to point out the total number of 4's in the the number entered and i have now encountered a problem..
This is my first post here so please excuse me if i make any mistakes..
The Code
int main()
{
int T,i,j,l;
char N,p[10];
cin>>T;
while(T--) //The number of times a user can enter a new number
{
cout<<"\nEnter Numbers\n";
l=0;i=0;
do
{
N=getch(); //getch is used so that the enter key need not be pressed and the
//number looks like a whole and also so the each number is
//individually stored
p[i]=N; //here the number entered is stored in p
cout<<N; //to display the number obviously
l++;i++;
}while(N!=' '); //Now here between '' something has to be present so that the loop
//terminates as soon as the enter key is pressed right now as soon
//as the spacebar is hit the loop will terminate.
cout<<"\n";
j=0;
for(i=0;i<l;i++) //using l so that the loop runs accordingly
{
if(p[i]=='4')
{
j++; //for couting the number of 4's
}
cout<<p[i]<<"\n"; //wont be needing in the final program but here cout is just
// to check the output
}
cout<<"\n THERE ARE "<<j<<" FOURS\n";
}
}
Please not that i already have a solution for my program so please DO NOT provide a different code using some different logic... i really need this very same program to work.i know that this program can be made to work using string length but here i want the loop to terminate after the enter key is pressed.
Well if you want to stop getting input when the user presses enter instead of space you need to test against '\r', '\n' or '\r\n' depending on what OS you are using. That said you really should be using standard C++ if you are going to use C++. You could easily make your code like:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
int loops;
std::cout << "How many numbers to check: ";
std::cin >> loops;
std::cin.get(); // eat newline
for (int i = 0; i < loops; i++)
{
std::string numbers;
std::cout << "Enter numbers and press enter: ";
std::getline(std::cin, numbers);
auto numberOf4s = std::count(numbers.begin(), numbers.end(), '4');
std::cout << "Number of 4's entered: " << numberOf4s << std::endl;
}
return 0;
}
Live Example
You can to see check if N is equal to '\r'. So your while loop looks like
do
{
N=getch(); //getch is used so that the enter key need not be pressed and the
//number looks like a whole and also so the each number is
//individually stored
p[i]=N; //here the number entered is stored in p
cout<<N; //to display the number obviously
l++;i++;
}while(N!='\r');

how to check if inputed value is valid value in c++

I checked many links on Stack and to other site. Most of it does it what is supposed to do, but not "exactly" how I want to. Here is the problem and the best solution that i found on online.
I want to enter a number, float for example and input should be checked if is a float or not.
I'm using this snippet found online. Also to mention that i need to repeat validation each time for loop its iterated.The "n" is entered separately before this function and its in "private".It does its job perfectly, except ...If you enter "55" (number), it checks and validates. That's ok.
If you enter "dfgfd" stuff (not a number), it checks and repeats question. That's ok.
If you enter "dfgdfgdg55",it checks and repeats question. It's also ok. If you enter "55dfgfd" stuff, it checks and NOT repeats. That's NOT OK.It just discarding characters after numbers.I want to discard this also.So correct input should be JUST "55" entered.(Number 55 is just a example number entered when prompted).Also I tried this on a simpler function "model".First to enter "55", second to enter "55gdf". They been presented on screen as "55" and "55". Then i added some code afterwards to compare these numbers. They are not the same!
#include <iostream>
using namespace std;
int Provera_kucanja()
{
cout<<endl;
cout<<"Input boundary for an array"<<endl;
cin>>n;
while (cin.fail() || !(n>0))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout<<"You didnt entered number, please try again... "<<endl;
cin>>n;
}
cout<<endl;
return 0;
}
float Unos_brojeva()
{
cout<<"\n";
cout<<"Now you must enter number into array:\n "<<endl;
for (int i = 0; i < n ; i++)
{
cout<<"Input "<<"["<<i<<"]"<<" number in array: ";
float r;
cin>>r;
while (cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout<<"You didnt entered number, please try again... "<<endl;
cout<<"Input "<<"["<<i<<"]"<<" number in array: ";
cin>>r;
}
unos[i]=r;
}
cout<<endl;
cout<<"Now show unsorted array members: "<<endl;
for(int i = 0; i < n; i++)
{
cout<<"This is "<<"["<<i<<"]"<<" member of array named 'unos': "<<unos[i]<<endl;
}
cout<<"\n"<<endl;
cin.get();
return 0;
}
int main(){
Provera_kucanja();
Unos_brojeva();
}
On the down side using suggested answers is that when user enters something like "ghfg" , result of this conversion is a ZERO!. So suggested answers is no-go's.
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string A_number;
char* An_array=new char[A_number.length()];
cout<<"Enter value for A_number: ";
cin>>A_number;
strcpy(An_array,A_number.c_str());
float n=atof(An_array);
cout<<"Value entered is: "<<n;
cin.get();
return 0;
}
The line:
cin >> r
is going to try to read a valid float, even if there is bad trailing information after it.
You are saying the problem occurs when someone enters 55x, in this case you think it should not be considered a valid number.
There is an answer to your problem here: https://stackoverflow.com/a/19717896/312594
What you have to do is read the entire data in as a string and confirm that only characters that are possible as float input (digits, ., +, -, etc.) are in the input, and in the correct possible order. Only after you validate the input do you convert the input to float (via cin or some other mechanism).
In most cases you should accept 55x as 55 since that's probably what the user wants, but if you do want to be strict you have to perform the additional validation yourself.
p.s. - I almost hate to say this as I do not want to sound biased, but as you're learning C++ you may find it useful to write all of your code, including prompts, in English. If you later ask for help on StackOverflow, it will be easier for more people to understand what you are trying to do and therefore to help you out.
Sounds like you want to read in the input as strings (or possibly whole lines), and then you can test those strings any way you like.