I've written a small program in C++ that prompts the user for input, the user gives a number, then the computer displays the number reversed.
For example: 17 becomes 71. 123 becomes 321.
This is the program:
#include <iostream>
#include <string> //for later use.
using namespace std;
int rev(int x)
{
int r = 0;
while(x)
{
r = (r*10) + (x%10);
x = x/10;
}
return r;
}
int main()
{
int nr;
cout << "Give a number: ";
cin >> nr;
rev(nr);
cout << nr;
return 0;
}
The final result of the program: prints the same number, function has no effect. What am I doing wrong? I tried several solutions but to no avail.
You need to change rev(nr); to nr = rev(nr);
or alternately change your function to:
void rev(int& x)
{
int r = 0;
while(x)
{
r = (r*10) + (x%10);
x = x/10;
}
x = r;
}
You're doing it right, but you're not grabbing your return value (the reversed value).
To solve this, just assign or print the return value:
cout << rev(nr);
or
nr = rev(nr);
cout << nr;
While probably not in the intended spirit, the simple answer is that if you're only going to display it in reverse, you can cheat and just work with a string:
std::string input;
std::cin >> input;
std::cout << std::string(input.rbegin(), input.rend());
You're not actually using the value that rev returns. You're just using the value nr which you pass to rev, and since you don't pass by reference, rev isn't being affected locally.
What you want to say is:
int nr;
cout << "Give a number: ";
cin >> nr;
int result = rev(nr);
cout << result;
return 0;
There is a std::reverse function in the STL, which works with collections.
#include <algorithm>
#include <iostream>
#include <string>
int main() {
long int i = 0;
do {
std::cout << "Gimme a number: " << std::endl;
} while (not (std::cin >> i)); // make sure it *is* a number
std::string display = std::to_string(i); // C++11
std::reverse(display.begin(), display.end());
std::cout << display << "\n";
}
Related
I am struggling to create a loop for getting input from user. The input must push_back() each instance.
#include <iostream>
#include <array>
#include <cstring>
#include <vector>
#include <string>
#include <string.h>
using namespace std;
int main()
{
vector <string> bookQ = { "what","book","is","that","you","are","reading" };
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
string input;
int x = 0;
for (x != '1') { // require a loop to input string and end when user prompts
cout << "Enter 1 to stop" << endl; //
cin >> x; //
getline(cin, input); //
bookQ.push_back(input); //
} //
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
Your for loop is missing the declaration and (iteration) expression parts:
for (declaration-or-expression; declaration-or-expression; expression)
so it should have looked like this:
for (;x != '1';) {
which is generally written as
while (x != '1') {
That would cause problems though since it would not stop directly when the user entered 1.
You are also comparing an int with a char ('1'), so in order to exit the loop, the user would have had to enter 49 (the ASCII value for 1), not 1.
You are also mixing formatted input (cin >> x) with unformatted input (getline). I suggest that you stick to one only.
Example:
while(cout << "Enter 1 to stop\n", getline(cin, input) && input != "1") {
bookQ.push_back(input);
}
Assuming you meant that input is a string, then you've made a few mistakes with types. First of all, you've used wrong type for variable x, you used int which is integer type, and the type string is required. Secondly, when comparing x with '1' you used single quotes, which define the type of variable as char, not string. To make 1 a string you should use double quotes, like so "1". Besides that, you have used for(condition), which is incorrect syntax. You should use while(condition). Also, when your loop iterates, the x variable is the input book name, and input variable is always an empty string, so I would suggest replace input with x everywhere. The working code is below.
P.S. I am not sure whether you want "1" to be in the final vector, so I haven't changed that
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> bookQ = {"what", "book", "is", "that", "you", "are", "reading"};
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
string input;
string x;
while (x != "1") {
cout << "Enter 1 to stop" << endl;
cin >> x;
bookQ.push_back(x);
}
for (int i = 0; i < bookQ.size(); i++) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
simply check if input is 1 everytime the user enters somthing, and when it does = 1, simply break loop.
string x;
while (true) { // require a loop to input string and end when user prompts
cout << "Enter 1 to stop" << endl;
cin >> x;
if (x == "1"){
break;
}
getline(cin, x);
bookQ.push_back(x);
}
}
First, your for syntax is wrong. You want a while loop instead, or in this case a do..while loop would make more sense. Also, you are pushing the user's input into the vector before validating what the input actually is.
Second, x is an integer, but '1' is a character whose ASCII value is number 49. Your loop will never end, because != will always be true. Since you want the user to enter number 1 to stop the loop, you need to drop the quotes:
Third, what is the point of pre-populating bookQ? Just declare the bookQ without any initial data, and then cout the entire question as a normal string. This way, after the user is done entering input, the vector will contain only the user's input and nothing else.
Try something more like this:
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
vector <string> bookQ;
string input;
cout << "what book is that you are reading" << endl;
do {
cout << "Enter a book, or 1 to stop" << endl;
getline(cin >> ws, input);
if (input == "1") break;
bookQ.push_back(input);
}
while (true);
for (size_t i = 0; i < bookQ.size(); ++i) {
cout << bookQ[i] << ' ';
}
cout << endl;
return 0;
}
I made here a program to do 3x+1 math problem. So I am asking, if I could write in a c++ code something like x/2;, or x*3+1. These stuff what i put here are with mistakes. Then, is it possible in c++ to do that? If yes, how?
Here's the code:
#include <iostream>
using namespace std;
int main() {
cout << "Write an integer.\n"; int x; cin >> x;
// I made here a program to do 3x+1 math problem.
while (x==1) {
if ((x%2)==0) {
x/2; cout << x << ", ";
} else if ((x%2)==1) {
x*3+1; cout << x << ", ";
}
}
return 0;
}
The output there was:
/tmp/GjudkYOaE4.o
Write an integer.
9
But I was waiting it to write the number 28, 14, and more, but it did nothing.
I can see that you are new to coding, I would suggest you to please read a good amount of information about if-elseif-else and while loop that you are using
I can show you a few corrections here
#include <iostream>
using namespace std;
int main() {
cout << "Write an integer.\n";
int x; cin >> x;
// I made here a program to do 3x+1 math problem.
while (x!=1) { // x!=1 could be one of the terminating condition so when your x becomes 1, the loop would end. But of course the terminating condition depends on what you are trying to achieve
if (x % 2 == 0) {
x = x/2; //you need to assign the value back to x
cout << x << ", ";
} else { // you dont need else-if here because there could only be 2 possibilities for %2 operaion here
x = x*3+1;
cout << x << ", ";
}
}
return 0;
}
Give value to the same variable with assignment operator ('='):
x = x*3+1;
or
x = x/2;
This is what I've tried so far
// Calculate the product of three integers
#include <iostream> // allows program to perform input and output
using namespace std;
// function main begins program execution
int main()
{
int x; // first integer to multiply
int y; // second integer to multiply
int z; // third integer to multiply
int result; // the product of the three integers
cout << "Enter three integers: "; // prompt user for data
cin >> x >> y >> z;
result = x * y * z;
}
what can i do to solve this question?
EDIT:
If you do not need it to loop use a if instead of a while.
Looks like you need to study some conditional statements try:
result = x*y*z;
while(result < 0){
cout << "Enter three integers: "; // prompt user for data
cin >> x >> y >> z;
}
cout << result << endl;
Should work fine...
I would suggest using a condition to check the number at the input itself:
#include <iostream>
int main() {
int inum1 = 0;
std::cin >> inum1;
if (inum1 < 0) { inum1 = 1; }
int inum2 = 0;
std::cin >> inum2;
if (inum2 < 0) { inum2 = 1; }
int inum3 = 0;
std::cin >> inum3;
if (inum3 < 0) { inum3 = 1; }
std::cout << inum1*inum2*inum3 << "\n";
return 0;
}
Notice that in my example I have used std::cout and std::cin instead of using namespace std
use of using namespace std is fine if you're a beginner or the program is small, but is discouraged for large programs :)
If you find typing std:: tedious, you can instead include the following statements:
using std::cin;
using std::cout;
Also, printf and scanf is usually preferred over cin and cout for fast I/O.
How can use the proper code to compare an input array with string?
#include<iostream>
#include<cstring>
#include<stdlib.h>
using namespace std;
int main()
{
char user[30] ;
string nama[5]="ali33,abu123,ahmad456,kasim123,rahmat123";
int w,i ;
cout<<"username : ";
cin>>user[30];
for(i=0;i>=0;++i)
{
w=strcmp(nama[i],user);
}
I'm using Dev-C++, and the error is on this line:
w=strcmp(nama[i],user)
Does anyone know how to fix this?
I suggest you study this:
std::vector<string> nama = { "ali33", "abu123", "ahmad456",
"kasim123", "rahmat123" };
string user;
cout << "username : ";
int w = -1;
if (cin >> user)
{
for(int i = 0; i < nama.size(); ++i)
if (nama[i] == user)
w = i;
if (w != -1)
std::cout << user << " found at [" << w << "]\n";
else
std::cout << user " not found\n";
}
Notes: use std::vector not arrays until you understand the differences, and std::string for any text. You could use the C++ Standard Library function std::find() to see if the user value appears in nama, but it's good to learn how to write a loop and do things yourself too.
`strcmp()`**is used when comparing c-string data types. Convert your char data type to string and use compare function as illustrated below**`
int main()
{
char user[30];
string nama[5] = { "ali33","abu123","ahmad456","kasim123","rahmat123" };
int w = -99;
int i;
cout << "username : ";
cin >> user[30];
string temp(user);
for (i = 0; i < 5; i++)
{
w = nama[i].compare(temp);
}
}
Like for example:
#include <iostream>
using namespace std;
int main()
{
for (int n=10; n>0; n--){
cout<< n <<", ";}
}
This will output the numbers 10,9,8,7,6,5,4,3,2,1
So is there a new way so I just get the last instance of the loop, the 1?
I new at this and google isn't giving me any answers.
There is no direct way to detect whether the current iteration of a for loop is the last one. But if the behavior of the loop is predictable, you can usually write code that can detect when you're on the last iteration.
In this case, you could do something like:
if (n == 1) {
cout << n << "\n";
}
in the body of the loop. (Of course it would be simpler in this case to replace the entire loop with cout << "1\n";, but I presume this is an example of something more complex.)
In more complicated cases, you can save whatever information you need in the body of the loop:
int value_to_print:
for ( ... ) {
value_to_print = i;
}
std::cout << value_to_print << "\n";
On each iteration, value_to_print is replaced by the current value of i. The final value is the value of i on the last iteration.
You could create a variable (outside the loop) to hold the "current" value of n; whatever happens to the loop (exit condition reached, break, an exception is thrown...) the value will stay there:
int last_n;
for (int n=10; n>0; n--) {
last_n = n;
cout<< n <<", ";
if (something) {
break; // works in this case
} else if (something else) {
throw some_random_error; // works in this case too
}
}
cout << "The last value of 'n' was " << last_n << endl;
You can use a simple if statement for that.
int main()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
if( n == 1 ) {
return n;
}
}
}
The simplest way to accomplish this is: -
#include <iostream>
using namespace std;
int main()
{
int x;
for (int n = 10; n > 0; n--){
x = n;
}
cout << x;
return 0;
}
I'm new to programming too and was trying to figure out something which will allow me to get the last instance of my loop as output.
I tried something and got the output, see if it can help you (if there's a mistake please let me know).
Here user input string is being replaced by "*" and instead of giving output of every instance i have made so only last instance is given as output.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
int string_length;//string length
cout<<"Enter your Email-ID: ";
cin>>str;
string_length = str.length(); //to give the length of input string and use it for the loop
cout<<"lentgh of the string: "<<string_length <<endl;
for(int x = 0; x <= string_length; x++){
str[x] = '*';
while(x==string_length) //string_length is the last instance of the loop
{
cout<<"Here's your Encrypted Email-ID: " <<str<<endl;
break;
}
}
return 0;
}