In my programming class, we have the following problem :
The user inputs an integer number. The program must make the sum of that number
and that number reversed. In other words, let's say the user input 1920. Here's what the program must do :
1920+0291=2211
Here's the code I came up with :
int main()
{
cout << "Entrer votre number entier" << endl;
int number;
cin >> number;
string numberInverse = to_string(number);
string numberComparatoire = numberInverse;
for (unsigned compteur = 0; compteur <= numberInverse.length(); compteur++){
numberInverse[compteur] = numberComparatoire[numberComparatoire.length() - compteur];
}
int numberInverseInt = stoi(numberInverse);
int somme = number + numberInverseInt;
cout << "Le number inversé est " << numberInverse << " et " << number << "+" << numberInverseInt << "=" << somme << endl;
return 0;
}
The names of the of the variables and the outputs are in french but that's not important.
I can build the solution to my code but upon running it, let's say I input 1920, my program shows mw an error message saying it had to abort and I don't understand why. Please help :( I know this is probably a bit of a beginner question in programming so guide me in my learnings.
Thank you very much!
Related
I working on an assignment for my introduction to programming class which is meant to perform operations on an array of grades. Here are the details:
Usinging the following parallel arrays:
const int NUM_GRADES =5;
string Students[NUM_STUDENTS] = {"Tom","Jane","Jo"};
int grades[NUM_STUDENTS][NUM_GRADES] ={{78,98,88,99,77},
{62,99,94,85,93},
{73,82,88,85,78}};
Write a function called displayNumStudentsAtLeastBForSelectedAssignment that takes the student and grade arrays as parameters, allows the user to select a valid assignment and locates and displays the number of the student with at least a grade >= 80 for that assignment in the format in the sample run below.
Here is the code I have written for this function. I am wondering if my logic makes sense as I was working on this all night and have just found a potential solution
//Displays the number of students with at least a B (>=80)
int DisplayNumStudentsAtLeastBForSelectedAssignment(string Students[NUM_STUDENTS], int grades[NUM_STUDENTS][NUM_GRADES])
{
std::cout << "Number of students with atleast a B: " << endl;
std::cout << "Please enter in an assignment number: ";
int assignmentNum;
std::cin >> assignmentNum;
getValidAssignmentNumber(assignmentNum);
int total =0;
for (int x = 0; x < NUM_STUDENTS; x++)
{
if (grades[x][assignmentNum-1]>= 80)
total = total + 1;
}
std::cout << "Number of students with at least B on assignment " << assignmentNum << ": " << total << endl;
}
The function seems to be working properly. Just curious if there is a more efficient way of doing it. Thank you all for the help in advance.
I'm trying to write in C++ a function (leggiInteroEstrIncl) that prompts the user to type by keyboard an integer number included in a given range (between minimo and massimo).
Following is the function I wrote and then a statement, in the main(), to invoke it:
#include <iostream>
using namespace std;
int leggiInteroEstrIncl(string stringaDaStampare, int minimo, int massimo) {
int numInserito = 0;
bool errore = false;
do {
errore = false;
cout << stringaDaStampare << " (un numero intero compreso tra " << minimo
<< " e " << massimo << " estremi inclusi): ";
try {
cin >> numInserito;
} catch (...) {
errore = true;
cout << "Hai inserito un numero non valido, prova ancora" << endl;
}
if (errore == false && (numInserito < minimo || numInserito > massimo)) {
errore = true;
cout << "Hai inserito un numero al di fuori dell'intervallo richiesto: "
<< minimo << " <-> " << massimo << endl;
}
} while (errore);
return numInserito;
}
int main() {
int number = 0;
number = leggiInteroEstrIncl(
"Inserire la cifra in Yen da ripartire in banconote e monete", 1, 30000);
system("pause");
return 0;
}
If I type a valid integer number which is not included in the specified range, this piece of software works and asks the user to type again, but if I type something which is not a number, for example the word "hello", this software goes in a sort of loop and doesn't stop to ask the user to type again.
Could you please tell me what is wrong with it?
Thank you
You can use std::string to get input:
string insertio;
cin >> inserito;
and then use one of this function:
http://en.cppreference.com/w/cpp/string/basic_string/stol
which throws proper exception if there isn't a number in string.
If you need to check more solutions, check this one:
How to determine if a string is a number with C++?
This
cin >> numInserito;
attempts to read in a number and nothing else.
It will succeed with a number, as you have observed.
With a non-number it will fail, but not in a way to trigger the catch part.
It will instead just not read anything in and especially it will leave the non-number in the input stream.
If you then continue trying to read in a number, it will continue failing.
When reading in a number fails you need to read in whatever there is and probably ignore it.
In order to ignore the non-number, read it in as a string and do nothing with it
(as described in the answer by BartekPL):
string insertio;
cin >> inserito;
I am running this code from textbook: An Intro To Design Patterns in C++ with QT.
/* Computes and prints n! for a given n.
Uses several basic elements of C++. */
#include <iostream>
int main() {
using namespace std;
/*
*/
// Declarations of variables
int factArg = 0;
int fact(1);
do {
cout << "Factorial of: ";
cin >> factArg;
if (factArg < 0) {
cout << "No negative values, please!" << endl;
}
}
while (factArg < 0);
int i = 2;
while (i <= factArg) {
fact = fact * i;
i = i + 1;
}
cout << "The Factorial of " << factArg << " is: " << fact << endl;
return 0;
}
The output console only prints one line that says "Factorial is: "
Is that what it's suppose to do?
Yes that is what the program should output at first; it's waiting for you to type a number. If you would step into your code you would soon find out that it will wait for an input on the following line " cin >> factArg;".
So... Go ahead, type a number and press enter :).
Yes you code includes cin >> factArgwhich you will input in the terminal first before the program will run. You may want to put the using namespace std before the main function rather then in it.
I`m trying to divide any number in .5, if dividing the number in .5 and my remain is 0 the number will raises up to the next. But if not, it will down to the next.
When I try to do that I get a issue in the line 39. Somebody can help me.
Thanks
//
// main.cpp
// Promedio
//
// Created by Oscar Espinosa on 3/27/15.
// Copyright (c) 2015 IPN ESIME Ticoman. All rights reserved.
//
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int ed, cv, qa, em, h, poo;
float prom, red;
string nom, ape;
cout << " Introduce tus datos" << endl
<<"Nombre: ";
getline(cin, nom);
cout << "Apellidos: ";
getline(cin, ape);
cout << "Introduce las siguientes calificaciones" << endl
<< "Ecuaciones Diferenciales: ";
cin >> ed ;
cout << "Calculo vectorial: ";
cin >> cv ;
cout << "Quimica apilcada: ";
cin >> qa ;
cout << "Electricidad y magnetismo: ";
cin >> em;
cout << "Humanidades II: ";
cin >> h;
cout << "Programacion orientada a objetos: ";
cin >> poo ;
prom = (ed+cv+qa+em+h+poo)/6.00;
if (prom%.5 == 0) // Semantic issue invalid operands to binary expression ('double' and 'double')
{
ceil(prom);
red = ceil(prom);
}
else
{
floor(prom);
red = floor(prom);
}
cout << nom << " " << ape << " tu promedio es " << prom << " y se redondea a " << red;
return 0;
}
#Oscar Espinosa you cannot use %(modulus) operator with double values So its showing the error invalid operands in expression.. try using the fmod(x,y) function..it will work
Modulo (%) can only be used with integer values.
You can use fmod but if you meant to work on integer values, perhaps such a trick can help:
if (10*static_cast< int >(prom)%5 == 0)
The issue is pretty clear: you don't define var before the if(var==0). In C++, you need to define the variable before its first use. Pay attention to what the compiler is telling you. In case of g++:
error: 'var' was not declared in this scope
which I think it's pretty explicit!
PS: don't modify the code after an answer, as you end up confusing everyone. In the actual code, you are passing 0.5 as the modulus operator argument. That operator takes an int. You need other way of testing whether a float is a multiple of 0.5. In particular, you should also pay attention to roundoff errors.
Hint: a float x is a multiple of 0.5 if and only if 2*x is an integer. So 2*x - floor(2*x) must be close to zero, i.e. abs(2*x - floor(2*x)) < 1e-12 to avoid floating point errors.
See related question: Checking if float is an integer
When I use this following code, the first string input is displayed correctly, but every string input afterwards is missing the first letter.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
//declare arrays
string cd_Name[20] = {""};
string cd_Artist[20]= {""};
//declare variables
int numCD = 0;
cout << "Enter number of CD's: ";
cin >> numCD;
if (numCD <= 20)
{
for (int x = 0; x < numCD; x++)
{
cout << "Enter name of CD " << x + 1 << ": ";
cin >> cd_Name[x];
cin.ignore();
getline(cin, cd_Name[x]);
cout << "Enter the artist of " << cd_Name[x] << ": ";
cin.get();
getline(cin, cd_Artist[x]);
cout << endl;
}//end of for loop
cout << "CD Names Artists" << endl;
cout << "======== =========" << endl;
for (int x = 0; x < numCD; x++)
{
cout << cd_Name[x] <<" "<< cd_Artist[x] << endl;
}//end of for loop
}
else
cout << "You can only enter a Max of 20 CD's" << endl;
//end of if
system ("pause");
return 0;
}//end of main function
An example of the output is shown below:
Enter the number of CD's: 3
Enter name of CD 1: The Battle of Los Angeles
Enter the artist of The Battle of Los Angeles: Rage Against the Machine
Enter name of CD 2: So Far So Good
Enter the artist of o Far So Good: Brian Adams
Enter name of CD 3: Amarte es un Placer
Enter the artist of marte es un Placer: Luis Miguel
CD Names Artists
========= ==========
The Battle of Los Angeles ise Against the Machine
o Far So Good rian Adams
marte es un Placer uis Miguel
I believe you will find this is caused by the cin.ignore() call.
the .ignore() of the istream base class functions by
Extract[ing] characters from the input sequence and discard[ing] them
The default value is to discard One (1) character.
In short,
cin >> cd_Name[x];
cin.ignore();
getline(cin, cd_Name[x]);
Will get the name inputted by the user, Ignore the first character, then extract the string to your array.
If you called cin.ignore(2) it would remove the first two characters, and so on.
Please view this article for more information (http://www.cplusplus.com/reference/istream/istream/ignore/)
[EDIT]
You may find your getline and ignore calls are arbitrary
try using this in your loop:
cin will deliver the resulting string directly into the variable given, you should not need getline, nor ignore to achieve this.
char Name_tmp[50];
char Artist_tmp[50];
for (int x = 0; x < numCD; x++)
{
cout << "Enter name of CD " << x + 1 << ": ";
cin.get(Name_tmp, 50); //get 50 character (max length of string) into string variable
cout << "Enter the artist of " << cd_Name[x] << ": ";
cin.get(Artist_tmp, 50); //get 20 character (max length of string) into string variable
cout << endl;
cd_Name[x] = Name_tmp;
cd_Artist[x] = Artist_tmp;
}//end of for loop
In short, I'm extracting a set number of characters (less can be taken, but no more) from the users input into a temporary C-string, then assigning those values into your array.
Note, I made use of the istream::get method.
[Edit 2]
I noticed David Schwartz's post as to the implementation of using
system ("pause");
Unfortunately, I believe David is an avid linux programmer, and is not familiar with Visual Studio - When a program in run from VS (unless done so without debugging) the program output window closes before you can view the results.
This may also occur with some other IDE's.
My recommendation is to use something like this instead
char tmp[20];
cin.get(tmp, 20);
return;
This will pause and wait for the user to provide some input (a return should count as input in the case of MS Visual Studio)