I have a simple program that converts decimal numbers to binary numbers. No errors come up when I run the program but I do get a single question mark. I should get a set of values like "00101" I am trying to use a function that returns a string as well. Here is my code,
#include <iostream>
using namespace std;
#include <string>
string convert(int num)
{
string binary;
int remainder;
while (num !=0 )
{
remainder = num % 2;
num = num / 2;
binary = remainder;
}
return binary;
}
int main()
{
int number;
string binaryNum;
cout << "Enter a Number:";
cin >> number;
binaryNum = convert(number);
cout << "This is your number in binary form:" << binaryNum << endl;
system("pause");
}
Any ideas?
Thanks for the help
There are several problems with this code. First, you are assigning the string binary using the = sign on the line binary = remainder. What you probably meant to write was binary += remainder, to append the remainder to the string.
The second problem is also on that line. Both string::operator= and string::operator+= have overloads that take a char. Those overloads are called, when you pass in an int. So the string is being set to the character whose ascii value is 0 or 1, thus the question mark character, which is not what you are looking for. You can use std::to_string to easily convert your int into a string. Or if you need any level of control over the formatting, you can use std::ostringstream as in this answer.
In other words, change binary = remainder; to binary += std::to_string(remainder).
Third problem: There is a return statement inside the while loop. The function will return after one iteration of the loop, no matter how large num is. Remove that return statement, so there is only the one at the very end of the convert function.
There is a basic problem with your code.
The while loop will iterate only once as you are returning a value.
You should concatenate binaryValue every time with remainder, and return it outside loop.
And I haven't checked the logic so do check it.
Related
I am very new to c++ and am trying to program a simple calculator. I would like to add an input option were if you type 'ans' it will replace the first number with the answer to the previous calculation. Unfortunately I already defined that input as a float which causes it not to read any string input. If I defined that input as a string, the calculator would crash because you cant multiply two strings. This is the piece of code I am stuck on.
#include <iostream>
int main()
{
float a;
std::cin >> a;
if (a == 'ans') {
std::cout << "this is a string input";
}
else {
std::cout << a * 2;
}
}
I believe that when ever I enter 'ans' it goes straight to the else part of the if and tries to multiply a * 'ans' because it returns 0.
If anybody has any idea...
Thanks
My suggestion would be to take a std::string as input, check whether it is "ans" or any other string input, and then, if it is not, convert it to a float using std::stof.
Also, keep in mind that 'ans' is not a string, but a multicharacter literal, as others have noted. This is not what you want here. In C++, use single quotes for character literals and double quotes for string literals.
There are many ways to overcome this problem. One of them is to use std::stof() which takes a std::string and size_t *, then returns the number contained in the std::string and in the same time the value of the var pointed to by the size_t * changes to the number of the processed chars of the std::string if its leading chars are numbers, as follows
#include <iostream>
#include<string>
int main()
{
std::string a{};
std::cout<<"Enter a thing: \n";
std::cin >> a;
size_t processedCharsNo{};
float num{};
if(!isalpha(a[0]))num = std::stof(a, &processedCharsNo);
if (processedCharsNo == 0) {
std::cout << "this is a string input";
}
else {
std::cout << num * 2;
}
}
Since the program executes the loops the correct amount of times, we know the division is working, however I cannot seem to get the output of whatever is in the string variable "result." Any help?
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int base,decimal,remainder;
string result;
cout <<"Welcome to the Base Converter. Please enter in the requested base from 2-16"<<endl;
cout <<"and an integer greater than or equal to zero and this will convert to the new base."<<endl
do
{
cout <<"Please enter the requested base from 2-16:"<<endl;
cin >>base;
}while (base<2 || base>16);
do
{
cout <<"Please enter the requested integer to convert from base 10:"<<endl;
cin >>decimal;
}while (decimal<0);
do
{
decimal=decimal/base;
remainder=decimal%base;
if (remainder<=9)
{
string remainder;
result=remainder+result;
}
else
{
switch(remainder)
{
case 10:
{
result="A"+result;
}
There are some more cases for my switch, but I believe the problem is somewhere in my variable declaration or my string class. Any obvious solutions?
The code you posted is incomplete and I can't be sure if this is the correct solution without seeing the rest of the function. However, the way you modify your result variable in the snippet you have posted is clearly incorrect.
When you declare a local variable with the same name as another variable in the given context, it hides the earlier declared one. So if you write
int remainder = 0;
std::string result = "";
if (remainder<=9)
{
std::string remainder; //this hides the outer-scope remainder variable for this code block
result=remainder+result;
}
it's the same as if you have written
result = "" + result;
which is clearly a no-op.
To prepend the remainder value to a string you should do it like that:
if (remainder<=9)
{
std::string remainder_str = std::to_string(remainder); //note different name and initialization value
result = remainder_str + result;
}
or simply
result = std::to_string(remainder) + result;
Please note that to_string is available since C++11 in header <string>. If you can't use C+11, you could use itoa instead.
I am fairly new to programming and have to create a program which reads the prompt: "I have 8 dollars to spend." It then needs to print out with each word on a separate line, and then if any of the strings is numeric, it needs to be divided by 2. Therefore it should end up printing out as:
I
have
4
dollars
to
spend.
I have managed to do everything, except finding the numeric value and dividing it by 2. So far I have this:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string prompt;
string word;
cout << "Prompt: ";
getline(cin, prompt);
stringstream ss;
ss.str(prompt);
while (ss >> word)
{
cout << word << endl;
}
return 0;
}
After looking through various other posts, I cannot manage to get this to work. I'm assuming its an if/else statement within the while loop along the lines of, if numeric, set int num to num / 2 then cout << num << endl;, else cout << word << endl;, but I can't figure it out.
Thanks in advance.
You can use the stringstream class, which handles conversions between strings and other data types, to attempt to convert a given string to a number. If the attempt is successful, you know
The stringstream object allows you to treat a string as though it is a stream similar to cin or cout.
Incorporate this into your while loop, like so:
while (ss >> word)
{
int value = 0;
stringstream convert(word); //create a _stringstream_ from a string
//if *word* (and therefore *convert*) contains a numeric value,
//it can be read into an _int_
if(convert >> value) { //this will be false if the data in *convert* is not numeric
cout << value / 2 << endl;
}
else
cout << word << endl;
}
The strtol (C++11 version that works on std::string directly: std::stol) function is really good for testing whether a string holds a number, and if so, what the numeric value is.
Or you could continue using iostreams like you have been... try extracting a number (int or double variable), and if that fails, clear the error bit and read a string.
I dont have 50 rep so I cant comment, thats why I'm writing it as answer.
I think you can check it character by character, using Ascii value of each char, & if there are ascii values representing numbers between two spaces(two \n in this case as you've already seperated each word), then you have to divide the number by 2.
This may be a total beginner's question, but I have yet to find an answer that works for me.
Currently, I'm writing a program for a class that takes in a user's input (which can be one or more numbers separated by spaces), then determines whether the number is prime, perfect, or neither. If the number is perfect, then it will display the divisors.
Thus far, I've already written the code for the prime, perfect, and listing the divisors. I'm stuck on the input portion of my program. I don't know how to get the input that's separated by spaces to go through my loops one at a time.
This is my current program:
cout<<"Enter a number, or numbers separated by a space, between 1 and 1000."<<endl;
cin>>num;
while (divisor<=num)
if(num%divisor==0)
{
cout<<divisor<<endl;
total=total+divisor;
divisor++;
}
else divisor++;
if(total==num*2)
cout<<"The number you entered is perfect!"<<endl;
else cout<<"The number you entered is not perfect!"<<endl;
if(num==2||num==3||num==5||num==7)
cout<<"The number you entered is prime!"<<endl;
else if(num%2==0||num%3==0||num%5==0||num%7==0)
cout<<"The number you entered is not prime!"<<endl;
else cout<<"The number you entered is prime!"<<endl;
return 0;
It works, but only for a single number. If anyone could help me to get it to be able to read multiple inputs separated by spaces, it'd be greatly appreciated. Also, just a side note, I do not know how many numbers will be entered, so I can't just make a variable for each one. It will be a random amount of numbers.
Thanks!
By default, cin reads from the input discarding any spaces. So, all you have to do is to use a do while loop to read the input more than one time:
do {
cout<<"Enter a number, or numbers separated by a space, between 1 and 1000."<<endl;
cin >> num;
// reset your variables
// your function stuff (calculations)
}
while (true); // or some condition
I would recommend reading in the line into a string, then splitting it based on the spaces. For this, you can use the getline(...) function. The trick is having a dynamic sized data structure to hold the strings once it's split. Probably the easiest to use would be a vector.
#include <string>
#include <vector>
...
string rawInput;
vector<String> numbers;
while( getline( cin, rawInput, ' ' ) )
{
numbers.push_back(rawInput);
}
So say the input looks like this:
Enter a number, or numbers separated by a space, between 1 and 1000.
10 5 20 1 200 7
You will now have a vector, numbers, that contains the elements: {"10","5","20","1","200","7"}.
Note that these are still strings, so not useful in arithmetic. To convert them to integers, we use a combination of the STL function, atoi(...), and because atoi requires a c-string instead of a c++ style string, we use the string class' c_str() member function.
while(!numbers.empty())
{
string temp = numbers.pop_back();//removes the last element from the string
num = atoi( temp.c_str() ); //re-used your 'num' variable from your code
...//do stuff
}
Now there's some problems with this code. Yes, it runs, but it is kind of clunky, and it puts the numbers out in reverse order. Lets re-write it so that it is a little more compact:
#include <string>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
num = atoi( rawInput.c_str() );
...//do your stuff
}
There's still lots of room for improvement with error handling (right now if you enter a non-number the program will crash), and there's infinitely more ways to actually handle the input to get it in a usable number form (the joys of programming!), but that should give you a comprehensive start. :)
Note: I had the reference pages as links, but I cannot post more than two since I have less than 15 posts :/
Edit:
I was a little bit wrong about the atoi behavior; I confused it with Java's string->Integer conversions which throw a Not-A-Number exception when given a string that isn't a number, and then crashes the program if the exception isn't handled. atoi(), on the other hand, returns 0, which is not as helpful because what if 0 is the number they entered? Let's make use of the isdigit(...) function. An important thing to note here is that c++ style strings can be accessed like an array, meaning rawInput[0] is the first character in the string all the way up to rawInput[length - 1].
#include <string>
#include <ctype.h>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
bool isNum = true;
for(int i = 0; i < rawInput.length() && isNum; ++i)
{
isNum = isdigit( rawInput[i]);
}
if(isNum)
{
num = atoi( rawInput.c_str() );
...//do your stuff
}
else
cout << rawInput << " is not a number!" << endl;
}
The boolean (true/false or 1/0 respectively) is used as a flag for the for-loop, which steps through each character in the string and checks to see if it is a 0-9 digit. If any character in the string is not a digit, the loop will break during it's next execution when it gets to the condition "&& isNum" (assuming you've covered loops already). Then after the loop, isNum is used to determine whether to do your stuff, or to print the error message.
You'll want to:
Read in an entire line from the console
Tokenize the line, splitting along spaces.
Place those split pieces into an array or list
Step through that array/list, performing your prime/perfect/etc tests.
What has your class covered along these lines so far?
int main() {
int sum = 0;
cout << "enter number" << endl;
int i = 0;
while (true) {
cin >> i;
sum += i;
//cout << i << endl;
if (cin.peek() == '\n') {
break;
}
}
cout << "result: " << sum << endl;
return 0;
}
I think this code works, you may enter any int numbers and spaces, it will calculate the sum of input ints
std::vector<int> num{};
int buf;
do{
std::cin >> buf;
num.push_back(buf);
}while(std::cin.peek() == ' ');
In C language you can to it using scanf like this:
scanf('%d %d',&a,&b);
I have to write a program that converts a decimal number between (1.0 - 99.99) into binary. My teacher said We can ONLY use the things we learned in class so far, witch include: Loops, input/output files, strings, if/else, cmath, and user defined functions. Ive started to program how to convert an integer to binary first before taking on the decimal. I am able to calculate the binary value but I am spitting out my binary in reverse order. So my teacher said to send the remainders(eg: bit values) to a file and read them as a string. Which is were I am now. Still with the same problem. How do I print these values from a string in reverse order?
My attempt so far:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int number;
int remainder;
string bitValues;
ofstream outFile;
ifstream inFile;
//inFile.open("C:\\Users\\David\\Desktop\\BinaryIn.txt"); // pay no mind to this.
outFile.open("C:\\Users\\David\\Desktop\\BinaryOut.txt");
cout << "Enter a integer to be converted to binary: ";
cin >> number;
while(number != 0)
{
remainder = number % 2;
outFile << remainder << " "; // I send it to the outFile
number /= 2;
}
outFile.close(); // I close because I need to read from it now.
inFile.open("C:\\Users\\David\\Desktop\\BinaryOut.txt"); //I did this so I can read from the same outFile
getline(inFile, bitValues); //had to look up getline(), was not covered in class
// I just came up with this idea, is this Valid??????????
int posisiton = 10;
while(posisiton >= 0)
{
cout << bitValues[posisiton]; // I ever done something like this but It worked!
posisiton--;
}
int pause;
cin >> pause;
return 0;
}
Do you know how to write a recursive function? By doing the recursive call before outputting the remainder (as opposed to afterwards), you will get the effect you want.
1) Forget the file (I don't know how that was going to help. Maybe you misunderstood the teacher). Just write a simple function to reverse the string.
for(int i=0; i<bitValues.length()/2; ++i) {
char t = bitValues[i];
bitValues[i] = bitValues[bitValues.length()-1-i];
bitValues[str.length()-1-i] = t;
}
2) Or instead of using modulo, use a flag to get the bits in order the first time. This isn't code because it more directly relates to your homework, than a simple string reversal.
resize the string to be big enough to hold all the bits
set a mask to have a 1 in the 31st position
for each position in the string
use `&` with the mask to find if it's a one or zero
set the character depending on the bit
shift the mask right one.