error: comp. bet. signed/unsigned integer expressions CODEBLOCKS - c++

the assignment is: have a number saved in a string, then convert from a string to an integer--> convert that number to a decimal number from N-base the user inputs.
#include <iostream>
using namespace std;
int main()
{
string snum;
int n=0, base, res;
cout << "enter n: ";
cin >> snum;
cout << "enter base: ";
cin << base; //THIS IS LINE 13
for (int i=0; i<snum.length(); i++) // des order
{
int digit = snum.at(i) - '0';
n = (n*1) + digit;
if (
base <= 10
) res = base * n;
cout << "n is " << res << endl;
}
}
Im getting error: NO MATCH BETWEEN SIGNED AND UNSIGNED INTEGER EXPRESSIONS [Line 13]
ty all!!
*if u find any problems in logic please let me know!
*using codeblocks

with
cin << base; //THIS IS LINE 13
you mean
cin >> base;
EDIT:
you should convert the number differently, instead of grabbing each character take the whole string and convert it to a number. You can use a stream for that or just atoi( sum.c_str() ) to get the integer number.
thereafter convert the value to whatever base you want.
e.g.
snum=12 (converted to integer from input string)
base=8
12 - 8 (>8, number of times you can subtract) --> 1
4 - 8 (<8 use remainder) --> 4
output == 14

Related

How to extract the first digit of a 16 digit number?

I have this code right here that compiles just fine getting the first digit of a 10 digit number.
I am wondering how to get my code to get the first digit of a 16 digit number?
I have tried changing 10 to 16 in the while loop and my program does not count the first digit. Here is my code down below:
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter a number : " << endl;
cin >> number;
// cout << "Last digit is : " << number % 10 << endl;
while(number >= 10)
{
number = number/10;
}
cout<< "First digit is : "<< number << endl;
return 0;
}
int has at least 16 bits. The exact size is implementation defined. Even with 32 bits the maximum value is 2147483647. You cannot store a 16 digit number in an int.
You can store numbers with more digits than any integer type can hold in a std::string. Because just reading some string from the user and printing the first character would be too much cheating, at least you should check that the user actually did enter a number:
#include <iostream>
#include <limits>
#include <cctype>
int main() {
std::cout << "max int : " << std::numeric_limits<int>::max() << "\n";
std::string number;
std::cin >> number;
for (const auto& c : number) {
if (std::isdigit(c) == 0) {
std::cout << c << " is not a valid digit !";
return 1;
}
}
if (number.size() > 0 && number[0] != '0') std::cout << number[0];
else std::cout << "invalid input";
}
Live Demo
Learning how to use <string> will prove very, VERY useful for you:
#include <iostream>
#include <string> //extremely useful
using namespace std;
int main()
{
string aux;
string number;
cout<<"Enter a number: "<<endl;
cin>>aux;
number=aux.substr(0,1); //create a substring of aux, starting from the first position (first argument) and getting only one character (second argument)
cout<<"First digit is "<<number<<endl;
return 0;
}
if you need the variable as int, use stoi():
int num=stoi(number);
if you want to be sure the input has 10 or 16 digits, use size():
int size=aux.size();
if (size!=10) //or 16, whatever you want
cout<<"invalid number"<<endl;
Changing 10 with 16 won't work at all, the problem is the upper limits of an int which is usually 2147483647, inputing values above this will not work, meaning the digit will always be 2.
What you need to do is to use a larger type. You can safely use long long int which can take 19 digits.
long long number;
It's max value is guaranteed to be 9223372036854775807 at least.
Ideally, if possible, you should extract the user input as a string, it would be a much easier task to then extract the first character as exemplified by largest_prime_is_463035818.

Disabling Implicit Casting in c++

Is it possible to disable implicit casting in C/C++.
Suppose I want to write a validity function that makes me enter only integers in range [1,10]
I have written:
#include <iostream>
using namespace std;
int main( )
{
int var=0;
cout << "Enter a number (Integer between 1 to 10) : ";
while( (!(cin >> var )) || (var > 10 ) || (var < 1) )
{
cout << "U nuts .. It can only be [1,10]\n";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
cout << "Enter a number (Integer between 1 to 10) : ";
}
cout << "\nYou entered : " << var;
return 0;
}
But if the user enters 9.5 it accepts it by converting the float 9.5 as 9 and storing it in var. I want any float entry to be treated as invalid entry. How do I achieve this most compactly.
I do not want to do something of this sort:
#include <iostream>
#include <cmath>
using namespace std;
int main( )
{
float var=0;
cout << "Enter a number (Integer between 1 to 10) : ";
while( (!(cin >> var )) ||(var < 1)|| (var > 10 ) || !(ceilf(var) == var) )
{
cout << "U nuts .. It can only be [1,10]\n";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
cout << "Enter a number (Integer between 1 to 10) : ";
}
cout << "\nYou entered : " << var;
return 0;
}
This serves my purpose . But what I want to know, that is there any way where a conversion from float to int - I can suppress or it can show it as false input.
Similar to the way cin >> var where var type is int - if we enter char it returns false condition. Can we achieve the same for float entry ?
Thanks
But if the user enters 9.5 it accepts it by converting the float 9.5 as 9 and storing it in var.
No it doesn't. If the the user enters 9.5, then cin >> var stops reading when it hits the . (and leaves it on the stream). There's no float-to-int conversion because you haven't read a float, just an int.
The fix is to read the rest of the input (after cin >> var), and make sure there's nothing bad left over after the end of the int.
If you want to validate all of the input, you will have to get the whole line first.
Try:
string line;
getline(cin, line); // gets whole line
char *endptr;
long int var = strtol(line.c_str(), &endptr, 10); // converts string to int
// now check that endptr points to end of the string
if (endptr<line.c_str()+line.length()) {
// extra characters found after the integer
}

C++ program to accept multiples inputs and put in an array using pointer

there's a problem facing me in this question :
"write a c++ console program to accept five
integers values from keyboard in one line separated by spaces . the program then stores the five values in an array using pointer . then print the elements of the array on the screen ."
I tried to make a string variable and accept 5 integers from user then convert it to integer but it doesn't work well because it doesn't take numbers after space .
any help guys ??
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main(){
string numbers;
getline(cin, numbers);
int arr[5];
int *ptr;
int values;
stringstream convert(numbers);
convert >> values;
cout << values;
}
It will only take one at a time, you need to add more calls to convert like so:
stringstream convert(numbers);
convert >> values;
cout << values;
convert >> values;
cout << " " << values;
convert >> values;
cout << " " << values;
The C++faq has a good section on this.
Without major modification, if you need to put the number directly into the array using a pointer, you can do this:
int *ptr = arr ;
convert >> *ptr++ ;
convert >> *ptr++;
convert >> *ptr++;
convert >> *ptr++;
convert >> *ptr++;
for( unsigned int i = 0; i < 5; ++i )
{
cout << arr[i] << " " ;
}
cout << std::endl ;
I successfully made it
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main(){
int arr[5];
string number;
cout << "Please enter 5 integers separeted with spaces " << endl;
getline(cin, number);
int *ptr = arr ;
stringstream convert(number);
convert >> *ptr++ ;
convert >> *ptr++;
convert >> *ptr++;
convert >> *ptr++;
convert >> *ptr++;
for( int i = 0; i < 5; ++i )
{
cout << arr[i] << " " ;
}
cout << std::endl ;
}
I the numbers variable is string you can search for first non space character using numbers.find_first_not_of(" "); and first space character by numbers.find_first_of(" "); then create a subset using substr(.....) now place the substr in another string variable. Now convert the substring to int. repeat the steps for number of times you need. i.e. place the whole code inside a while loop. Terminate the loop whenever numbers.find_first_of(" ");returns numbers.end()

How do you check the length of a double in C++

I'm using this code to check that a student number being entered is the correct number of digits. Is there a function like .length() that will work for the variable type double? Thanks!
do {
cout << "Student's number: (Numeric only)";
cin >> studentNumber;
cin.ignore();
}
while (studentNumber.length() != 6);
Read it as a string, check it's length while it is still in that representation (also check that it consists only of [0-9]), then convert to a double. Actually, only convert to a double at all if you are going to do math with it. Otherwise keep it as a string.
In general taking user input in non-string types is fraught with danger. Read it as a string, validate and convert.
Read it as text, validate it, then parse it:
std::string input;
bool valid = false;
while (!valid) {
cout << "Student's number: (Numeric only)";
cin >> input;
if (input.size() == 6)
valid = true;
}
double studentNumber = strtod(input.c_str());
do {
cout << "Student's number: (Numeric only) " << flush;
} while( !( cin >> studentNumber ) ||
( studentNumber < 100000 ) ||
( studentNumber > 999999 ) );
Placing cin >> studentNumber within the while also ensures that the text entered by the user was successfully converted to what ever type studentNumber is.
Can't you just use < and >?
// Require that studentNumber be 3 digits
if(studentNumber < 100 || studentNumber >= 1000) {
cout << "bad" << endl;
}
If you switch to an integral type, simple division can accomplish this:
long studentNumber;
do {
// get number
} while (!(studentNumber / 100000L) || studentNumber / 1000000L);
If you actually want the number of digits in an integral type:
int long_digits(long l)
{
// this code will work for negative numbers, but we don't want them
if (l < 0L)
throw std::out_of_range("no negative numbers please");
int count;
for (count = 0; l; l /= 10L, ++count);
return count;
}
Why don't you use log10? then you need to round downthe result, maybe using floor(double) to find the integer
//remember math.h
#include <math.h>
do {
cout << "Student's number: (Numeric only)";
cin >> studentNumber;
cin.ignore();
}
while (floor(log10(studentNumber)) != 6);
EDIT:
A little explanation: log10 allows you to find x in this equation
10^x=y
where y is given and is your exponent.
Long story short, studentNumber must be of 6 'chars', we can write this as
10^5 <= studentNumber < 10^6
or
5 <= log10(studentNumber) < 6
and then
floor(log10(studentNumber)) ==5
only if it is a number of 6 digits in the integer part.

Input an integer, get spaced output in C++?

I'm working on homework and I'm stumped on this problem: Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, it should output the individual digits of 3456 as 3 4 5 6, [...], output 4000 as
4 0 0 0, and the individual digits of -2345 as 2 3 4 5.
Here's my code so far:
int main()
{
string a; //declares string
cout << "Type an integer: "; //prompts user to input an integer
cin >> a; //stores into string a
cout << "There are " << a.size() << " digits in " << a << endl; //retrieves length of string a
cout << a.at(0);
cout << endl;
system ("pause"); //pauses the system so user can read the screen
return 0; //returns 0 if program works properly
}
Can anyone enlighten me on what I'm doing wrong/what my next step is?
So the steps are..
store the input
display them all one by one separated by spaces
figure out the sum and display that
.
#include<string>
#include<iostream>
using namespace std;
int main()
{
string a;
cout << "Type an integer: ";
// 1. store the input
cin >> a;
// 2. display them all one by one separated by spaces
for(int i=0;i<a.size();++i)
cout << a[i] << ' ';
cout << endl;
// 3. figure out the sum and display that
int total = 0;
for(int i=0;i<a.size();++i)
total += a[i] - '0';
cout << total << endl;
system("pause");
return 0;
}
The tricky part is getting the correct sum in step 3.
total += a[i] - '0';
Lets say for example that a[i] is the character '4'. The ASCII value of character '4' is the integer equivalent of 52, and the ASCII integer equivalent of '0' is 48. Therefore if we take '4' - '0', we will get the difference of 4, which is the integer representation we are looking for in this case.
Here is a simple ASCII chart with character values.
Hope this helps!
You probably want to input the number as a string. This will allow you to do digit by digit processing. Then the user will enter the number once instead of many times as digits.
You could try this piece of code:
int num = 0;
cin>>num;
//Make sure array is large enough to hold all digits
//For an int 10 digits it the max
int digits[10] = {0};
//This variable tracks the count of actual number of
//digits extracted from user input
int digitCount = 0;
while (num > 0)
{
digits[digitCount] = num % 10; //Extract digit at units place
num = num / 10; //Advance through the number
digitCount++;
}
for(int count= digitCount-1 ; count >= 0; count-- )
{
cout<<digits[count]<<" ";
}
Note that the printing loop runs backwards (i.e from digitCount to zero) because the digits are extracted and stored starting from the units place. For a number a like 12345 the digits array will contain 5 4 3 2 1.
Rhonda, I can understand your frustration, computers are like that... they do what you say, not what you mean :-) Hang in there.
You say your program should output each of the digits in the number, yet your program asks the user to enter each of the digits. That is confusing.
Also, you first assign a value to "num" here
cin >> num;
then you overwrite "num" in this line
cin >> num >> a;
I'm not sure what you mean to do here, but what you're telling the computer to do is to read an integer from the input and assign it to "num" and assign the rest to the line to string "a"... if the rest of the line just has a space, the space will be discarded... it acts as a separator. That is probably confusing you as well.
int main()
{
int runningTotal = 0;
std::string inputString;
std::cin >> inputString;
for ( std::string::iterator _it = inputString.begin();
_it != inputString.end(); ++_it )
{
// *_it now represents an individual char of the input string
char a = *_it; char* b = &a;
if ( a != '-' )
{
runningTotal += atoi( std::string( b ).c_str() );
std::cout << *_it << " ";
}
}
std::cout << std::endl << "Total of all digits: " << runningTotal << std::endl;
std::cin.get();
std::system( "pause" );
return 0;
}
I threw this together quickly for you. Hope it's of help.