C++ read number string and capture specific position character as int - c++

I need my program to read a string of numbers input by the user and then assign each number to an int variable:
94715 is input by the user as string
then
a=9
b=4
c=7
d=1
e=5
so I can
if (a < b), c*d+e, a-e, etc
I've searched some commands (getline, string.substr(ind,n), getc, fgetc, atoi, etc) I know I'm close but I can't find examples of exactly what I'm looking for.
The simplest and most direct way I've found is
stringstream convert(string1);
convert>>variable;
but it converts the whole string, if there was a way to add an ind position in it like
string1.substr(0,1)
that'd do the trick...

It is as simple as this:
std::string num = "94715";
size_t i = 0;
assert( num.length() > 4 );
int a = num[i++] - '0';
int b = num[i++] - '0';
int c = num[i++] - '0';
int d = num[i++] - '0';
int e = num[i++] - '0';
note: this may not work properly on systems not using ACII encoding, but it is unlikely you would hit such problem.

int number = 9544;
int vector[10]; // you can make it as big as you want or simply use std::vector
int position = 0;
while (number != 0)
{
vector[position++] = number % 10; // this assigns the last digit
number = number / 10; // remove the last digit
}
for(int i=0; i<position; i++)
std::cout << vector[i]; // this will print 4459
Now you have your number's digits inside an int vector.

This example uses chars because a string is still a char array.
This is for if you are on Windows. Just input and press the enter key.
Like Dieter Lücking suggested, it does this character by character.
It uses kbhit() and getch() found in conio.h to process single characters.
Then it multiplys the characters with appropiate position to get full integer.
And then it stores them in the array digitArray[ ], and assigns them to a,b,c,d or e after. Now you can do whatever with a,b,c,d and e.
Here is some code to demonstrate.
// Re: Now it is just clunky
// one ten hundred thousand
// 1 2 3 4
//digitn=digitArray[3]*1 + digitArray[2]*10 +digitArray[1]*100 +digitArray[0]*1000
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
using namespace std;
int digit=0,digitInput=0;
int digitArray[10]={0},digitn;
int numberOfInputDigits=7;
void SplitIntoDigits(void);
int a=0,b=0,c=0,d=0,e=0,f=0;
int main(){
system("color 1F"); //Blue background
while(1){
cout<<"\nPlease enter number. Max Input is "<<numberOfInputDigits<<" individual digits \n";
cout<<"or press enter when done \n>" ;
memset(digitArray,0,sizeof(digitArray));
a=0;b=0;c=0;d=0;e=0;f=0;
SplitIntoDigits();
//cout<<"\n"<<digitArray[7]="<<digitArray[7];
cout<<"\n\n";
a = digitArray[0];
b = digitArray[1];
c = digitArray[2];
d = digitArray[3];
e = digitArray[4];
f = digitArray[5];
cout<<"a = "<< a <<"\n";
cout<<"b = "<< b <<"\n";
cout<<"c = "<< c <<"\n";
cout<<"d = "<< d <<"\n";
cout<<"e = "<< e <<"\n";
cout<<"f = "<< f <<"\n";
cout<<"\n\n The whole combined int number is "<<digitn<<"\n\n";
}
return 0;
}
/*********************************
* *
********************************/
void SplitIntoDigits(void){
digitArray[0]=0;
digitArray[1]=0;
digit=0;
digitInput=0;
while((digit<numberOfInputDigits)){
if (kbhit()){
digitInput=getch();
if (digitInput==27) exit(0);
if ((digitInput>47) && (digitInput<59)) {
digitArray[digit]=(unsigned char)digitInput-48;
digit++;
cout<<digitInput-48;
}
if (digitInput==13) { digitn=digitArray[0]; break; }
}
}
switch(digit) {
case 0:
case 1:
digitn=digitArray[0]*1 ;
break;
case 2:
digitn= digitArray[1]*1 +digitArray[0]*10 ;
break;
case 3:
digitn= digitArray[2]*1+digitArray[1]*10 +digitArray[0]*100 ;
break;
case 4:
digitn=digitArray[3]*1+digitArray[2]*10+digitArray[1]*100+digitArray[0]*1000 ;
break;
case 5:
digitn=digitArray[4]*1+digitArray[3]*10+digitArray[2]*100+digitArray[1]*1000+digitArray[0]*10000 ;
break;
case 6:
digitn=digitArray[5]*1+digitArray[4]*10+digitArray[3]*100+digitArray[2]*1000+digitArray[1]*10000
+digitArray[0]*100000;
break;
case 7:
digitn=digitArray[6]*1+digitArray[5]*10+digitArray[4]*100+digitArray[3]*1000+digitArray[2]*10000
+digitArray[1]*100000 +digitArray[0]*1000000;
break;
case 8:
digitn=digitArray[7]*1+digitArray[6]*10+digitArray[5]*100+digitArray[4]*1000+digitArray[3]*10000
+digitArray[2]*100000 +digitArray[1]*1000000+digitArray[0]*10000000;
break;
case 9:
digitn=digitArray[8]*1+digitArray[7]*10+digitArray[6]*100+digitArray[5]*1000+digitArray[4]*10000
+digitArray[3]*100000 +digitArray[2]*1000000+digitArray[1]*10000000 +digitArray[0]*100000000;
break;
}
// if (digitInput!=13) digitn=digitArray[3]*1+digitArray[2]*10+digitArray[1]*100+digitArray[0]*1000 ;
//cout<<("\n%i\n\n",digitn);
}
/*********************************
* *
********************************/

Related

how to print multiple numbers to words

in my code, i don't understand why zero doesn't print i did all possible solutions that I know but it doesn't print zero.
#include <iostream>
using namespace std;
int main(){
int digits;
int numberOne = 0;
int integer;
cout<<"Enter the number: ";
cin>>digits;
while (digits != 0) {
numberOne = (numberOne * 10) + (digits % 10);
digits /= 10;
}
for (integer = numberOne; integer > 0; integer = integer / 10){
switch (integer % 10) {
case 0:
cout<<"Zero\n";
break;
case 1:
cout<<"One\n";
break;
case 2:
cout<<"Two\n";
break;
case 3:
cout<<"Three\n";
break;
case 4:
cout<<"Four\n";
break;
case 5:
cout<<"Five\n";
break;
case 6:
cout<<"Six\n";
break;
case 7:
cout<<"Seven\n";
break;
case 8:
cout<<"Eight\n";
break;
case 9:
cout<<"Nine\n";
break;
}
}
return 0;
}
zero doesn't print how do I fix it?
Expected output is 900 (nine zero zero) but zero doesn't print in my case. help thanks.
Because in this line:
for (integer = numberOne; integer > 0; integer = integer / 10){
the loop continues only if integer>0. Therefore you never see "Zero".
Why doesn't it print zero? Look at your loop
for (integer = numberOne; integer > 0; integer = integer / 10){
If integer equals zero then the loop is never entered. You need to be a bit smarter in your loop. How about counting digits?
int num_digits = 0;
while (digits != 0) {
numberOne = (numberOne * 10) + (digits % 10);
digits /= 10;
++num_digits;
}
Now that you have the number of digits, you can use that in your second loop
for (integer = numberOne; num_digits > 0; integer = integer / 10, --num_digits) {
...
}
You still need to treat zero as a special case, because if the user enters 0 then num_digits will equal zero and you again won't print anything. I'll leave you to figure out how to fix that.
#include <iostream>
using namespace std;
int main(){
int digits;
int arrayLength = 10;
cout<<"Enter the number: ";
cin>>digits;
string reverse_number[arrayLength]; //array to store the string of numbers like "Zero"
int array_counter=0;
while (digits != 0) {
switch (digits % 10) {
case 0:
reverse_number[array_counter++] = "Zero";
break;
case 1:
reverse_number[array_counter++] = "One";
break;
case 2:
reverse_number[array_counter++] = "Two";
break;
case 3:
reverse_number[array_counter++] = "Three";
break;
case 4:
reverse_number[array_counter++] = "Four";
break;
case 5:
reverse_number[array_counter++] = "Five";
break;
case 6:
reverse_number[array_counter++] = "Six";
break;
case 7:
reverse_number[array_counter++] = "Seven";
break;
case 8:
reverse_number[array_counter++] = "Eight";
break;
case 9:
reverse_number[array_counter++] = "Nine";
break;
}
digits /=10;
}
int num_digits = array_counter;
for (int i = 0; i < num_digits; i++) {
cout << reverse_number[--array_counter] <<" ";
}
return 0;
}
The reason why your zeros are not showing while doing for 900 is because when you are reversing 900 to 009, there is no condition mentioned to handle the leading zeros in 009 which are just ignored. For this the best approach would be to store them somewhere else like in a string or an array. You can also just store the number words directly to an array while you are converting, that way you wont lose the leading zeros.
The other answers have already addressed the main problem with your code.This answer focus on the post's title: how to print multiple numbers to words?
First, I would consider using an array of strings instead of a switch.
In order to retrieve a string for a given digit, you would just index that array.(see digits[c - '0'] below)
Also, if you are allowed to convert a number to a string, the code would reduce to walking that string and converting each character to a word.You could read the number directly as a string from the standard input, or use std::to_string on an integer.
Notice also that, when reading a character c from the a string of digits, c - '0' gives you an integer betweeen 0 and 9, which you can use as the array index.
Demo
#include <array>
#include <iostream>
#include <string> // to_string
std::array<std::string, 10> digits{
"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"
};
void digits_to_words(int n) {
for (unsigned char c : std::to_string(n)) {
std::cout << digits[c - '0'] << "\n";
}
}
int main() {
for (int n : { 0, 5, 105, 900 }) {
std::cout << "Number: " << n << "\n";
digits_to_words(n);
std::cout << "\n";
}
}

Basic program to convert Roman number Arabic form?

I am wanting some help in answering these two questions. The first one is this:
I am trying to write a program that converts a single Roman number in the range I (1) to IX (9) to Arabic form. The
program should read a single string from standard input and print the corresponding value to standard output.
I then want to Extend the program so that it works correctly when the input consists of either lower case or upper case Roman letters.
The simplest approach is to convert each character in the input word into uppercase before trying to find a match. Run a
loop over the characters in the string using the index operator ([]) to access each character and use the toupper
function (you will need to include the cctype header file) to get the corresponding uppercase value.
For the second question this is what it wants me to do next:
Extend the program so that it can deal with single digit numbers of any value. A single digit number is one that consists
only of thousands, hundreds, tens, or units. Thus LXX (70) and CD (400) are single digit numbers, but XIV (14) and
MC (1100) are not. Use the same approach as for units digits, but with 4 different arrays, one each for the thousands,
hundreds, tens, and units digits. Try looking for thousands digits first, then for hundreds, and so on. When you find a
match in one of the arrays, print the corresponding value and stop.
Modify the program so that it reads and converts all input numbers until end of file (eof) on standard input. You will
probably be able to do this by simply adding an appropriate reading loop around the code that reads a single line.
Currently this is what i have to start but am unsure how to write a program like this:
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
class RomanNumeral
{
public:
const static int M = 1000;
const static int D = 500;
const static int C = 100;
const static int L = 50;
const static int X = 10;
const static int V = 5;
const static int I = 1;
RomanNumeral( const int arabic ) :
m_roman( "" ),
m_arabic( ((arabic > 0) ? arabic : 0) )
{
if( arabic > 0 )
{
int i = arabic;
while( i > 0 )
{
if( ( i - M ) >= 0 )
{
m_roman += "M";
i -= M;
continue;
}
if( ( i - D ) >= 0 )
{
m_roman += "D";
i -= D;
continue;
}
if( ( i - C ) >= 0 )
{
m_roman += "C";
i -= C;
continue;
}
if( ( i - L ) >= 0 )
{
m_roman += "L";
i -= L;
continue;
}
if( ( i - X ) >= 0 )
{
m_roman += "X";
i -= X;
continue;
}
if( ( i - V ) >= 0 )
{
m_roman += "V";
i -= V;
continue;
}
if( ( i - I ) >= 0 )
{
m_roman += "I";
i -= I;
continue;
}
}
}
else
{
m_roman = "0";
}
}
RomanNumeral( const std::string& string ) :
m_roman( ((string.size() > 0 ) ? string : "0" ) ),
m_arabic( 0 )
{
int i = 0;
while( i < (int)string.size() )
{
char c = string[i++];
switch( c )
{
case 'M':
case 'm':
m_arabic += M;
break;
case 'D':
case 'd':
m_arabic += D;
break;
case 'C':
case 'c':
m_arabic += C;
break;
case 'L':
case 'l':
m_arabic += L;
break;
case 'X':
case 'x':
m_arabic += X;
break;
case 'V':
case 'v':
m_arabic += V;
break;
case 'I':
case 'i':
m_arabic += I;
break;
default:
throw new std::out_of_range( "Not a valid Roman numeral!" );
break;
}
}
}
int getArabic()
{
return m_arabic;
}
void setArabic( const int arabic );
const std::string& getRoman()
{
return m_roman;
}
protected:
std::string m_roman;
int m_arabic;
};
int main()
{
std::string roman;
cin >> roman;
try
{
RomanNumeral rn( roman );
cout << rn.getArabic() << endl;
}
catch( exception* ex )
{
cout << roman << " " << ex->what() << endl;
}
return 0;
}
Have been doing some tutorials on it but came across this question on a website the other day but I can't find the solution to this to see how its done. Could you demonstrate how to write a program like this by any chance?
Whenever you're stuck on a problem, try to decompose it into steps and implementing the things you can.
Step one is reading a single word:
std::string word;
std::cin >> word;
Step two is converting the word into a number:
int convert_to_number(const std::string& w) {
if (w == "I") return 1;
if (w == "II") return 2;
// and so on.
}
Step three is doing the conversion and printing the result:
std::cout << convert_to_number(word) << std::endl;
Instead of writing large amounts of if statements, you may want to try using an std::map<std::string, int> or std::unordered_hash<std::string, int> for a constant-time lookup.

C++ sum of odd digit

I have created a program in which the function can add all the odd digits; however, I would like print out all the odd digits, for example, sum_odd_digits(2139) return 1+3+9 = 13 while sum_odd_digits(1024) return 1.
#include <iostream>
using namespace std;
int sum_odd_digits(unsigned int i){
unsigned int a =0;
while ((i !=0)&&(i%2 !=0)){
a +=i%10;
i/=10;
}
cout << a;
}
int main(){
sum_odd_digits(2139);
}
Anyone can give me some tips for printing out odd digits?
Thanks for your help
This is it:
int sum_odd_digits(unsigned int i){
unsigned int a = 0;
while (i != 0){
if ( i % 2 == 1 )
cout << i % 10 << ' ';
a += i % 10;
i /= 10;
}
return a;
}
It looks through all digits, and if digit is odd it prints it. It return digits sum.
You're on the right track. The following example separates the digits of a number, and prints them if they are odd.
Code Listing
#include<stdio.h>
int main(){
int num,temp,factor=1;
printf("Enter a number: ");
scanf("%d",&num);
temp=num;
while(temp){
temp=temp/10;
factor = factor*10;
}
printf("The odd digits of the number are: ");
while(factor>1){
factor = factor/10;
switch (num/factor) {
case 1:
case 3:
case 5:
case 7:
case 9:
printf("%d ",num/factor);
break;
}
num = num % factor;
}
return 0;
}
while ((i !=0)&&(i%2 !=0))
This will stop as soon as either condition is false; when i becomes zero, or when the value is even. However, you don't want to stop when you find the first even value, you want to continue testing digits and only stop when i becomes zero. So this should be structured as
while (i != 0) {
if (i % 2 != 0) {
// final digit is odd
a += i%10;
}
i/=10;
}
You could compress the first an last lines into a for loop if you like
for (; i != 0; i /= 10)

C++: Hex to Decimal Conversion Function - Not getting correct output

I'm trying to convert hex values to decimal. I'm just trying to extract either a number (0-9) or letter (A-F), which I'm converting to the number value with another function, and then push the values into a stack (I could have used vector, but chose stack this time). I'm then just trying to get the decimal value, and since a stack works backwards, it should be in order.
The correct output, as shown below, should be 1728, but I'm getting 12.
Thanks in advance.
#include <iostream>
#include <string>
#include <math.h>
#include <stack>
using namespace std;
int hexCharToDec(char a);
void hexToDecimal(string str, stack<int> & myStack);
int main(){
stack<int> myStack;
string str = "6C0"; // should be 1728
hexToDecimal(str, myStack);
}
void hexToDecimal(string str, stack<int> & myStack){
int totalVal = 0;
for (int i = 0; i < str.length(); i++){
if (str.at(i) <= 9)
myStack.push(str.at(i));
else if (str.at(i) >= 'A' && str.at(i) <= 'F')
myStack.push(hexCharToDec(str.at(i)));
}
int k = 0;
for (int i = 0; i < myStack.size(); i++){
totalVal += (myStack.top() * pow(16, k++));
myStack.pop();
}
cout << totalVal;
}
int hexCharToDec(char hexChar){
switch(hexChar){
case 'A':
return 10;
break;
case 'B':
return 11;
break;
case 'C':
return 12;
break;
case 'D':
return 13;
break;
case 'E':
return 14;
break;
case 'F':
return 15;
break;
}}
In the original version of the code you posted, you mixed up 0 with '0' and likewise for the other digits. The output was 12 because if you take 6C0 and ignore the 6 and 0, the result is C which is 12.
In the updated version this loop is broken:
for (int i = 0; i < myStack.size(); i++)
{
totalVal += (myStack.top() * pow(16, i));
myStack.pop();
}
When you do pop(), it reduces size(). So you only actually process half of the digits in the stack (rounded up). To fix this, loop until myStack.size() == 0 instead.
The problem is that the characters you're inputting aren't in the range of your if statements. The digit characters don't have the values 0-9, they are '0'-'9' - a different thing altogether. Those characters don't get processed at all.
In addition, your for loop is looping over the size of the stack - but the size of the stack is changing as you pop things off the end. You're only processing half of the input.
A working solution:
#include<iostream>
#include <string>
#include <sstream>
int main()
{
int n;
string str = "6C0";
istringstream sin(str);
sin>>hex>>n;
cout<<n<<endl;
return 0;
}

Write multiple things in a switch statement in C

So i need to have my switch statement go through and write out five two if the user says 52 but i cannot get it pass my 0-9. if they type 0-9 it works perfect but if i try to do any number past that it makes a blank. help!
#include <stdio.h>
int main (void)
{
int x;
printf("Please enter an integer: ");
scanf("%d", &x);
printf("\nYou have entered:\n\n");
for(x;x<0;x++);
switch (x)
{
case 0:
printf("zero");
break;
case 1:
printf("one");
break;
case 2:
printf("two");
break;
case 3:
printf("three");
break;
case 4:
printf("four");
break;
case 5:
printf("five");
break;
case 6:
printf("six");
break;
case 7:
printf("seven");
break;
case 8:
printf("eight");
break;
case 9:
printf("nine");
break;
}
printf("\n\n");
return 0;
}
do {
switch (x%10) {
...
}
x = x / 10;
} while (x>0) ;
or to get it in the right order use recursion
void f(int x) {
if (x==0) return;
f(x/10);
switch(x%10) { ... }
}
This question has been asked-and-answered before.
The for-loop you wrote is empty, because the body of the loop ends with the semi-colon:
for(x;x<0;x++) /* Empty Body!!*/ ;
The way a typical for loop works is:
for( /*Initialize*/; /*Test*/; /*Change*/)
{
/* Body */
}
In your case, I think you want:
for(int i=0; i < x; ++i)
{
switch(x)
{
[...]
}
}
This will:
Initialize i to 0
Test if i is LESS THAN x (the number you entered)
Keep increasing i by 1, until it gets up to x.
I'm not going to do your homework for you but consider the following pseudo-code:
print_text_digits(x)
{
if (x >= 10) print_text_digits(x / 10);
switch (x) {
print "zero" through "nine" as appropriate
}
}
main()
{
scan number into x;
print_text_digits(x);
}
This relies on a recursive routine so that you get your digits processed one at a time, with the might significant digit printed first.
You could solve this with recursion.
void printDigit(int x) {
int digit = x%10;
if(digit!=x)
printDigit(x/10);
switch(digit) {
...
}
}
This will print the most significant figure first, unlike the while loops most people are mentioning.
I believe you need this:
#include <stdio.h>
int main (void)
{
int count = 0;
int x, count2;
printf("Please enter an integer: ");
scanf("%d", &x);
printf("\nYou have entered:\n\n");
int aux = x;
while(aux>0) {
aux=aux/10;
count++;
}
count2 = count;
while(count) {
aux = x;
for(int i=count-1;i>0;i--)
aux=aux/10;
for(int i=count2-count;i>0;i--)
aux%=10;
switch (aux) {
case 0:
printf("zero");
break;
case 1:
printf("one");
break;
case 2:
printf("two");
break;
case 3:
printf("three");
break;
case 4:
printf("four");
break;
case 5:
printf("five");
break;
case 6:
printf("six");
break;
case 7:
printf("seven");
break;
case 8:
printf("eight");
break;
case 9:
printf("nine");
break;
}
count--;
if(count) printf(" ");
}
printf("\n\n");
return 0;
}
Now, with an input 52 it will propelly return five two.
#include <stdio.h>
static const char * const num[] = {
"zero ", "one ", "two " , "three ", "four ",
"five ", "six ", "seven ", "eight ", "nine "
};
void printNum(int x)
{
if (x < 10) {
printf(num[x]);
return;
}
printNum(x / 10);
printNum(x % 10);
}
int main (void)
{
int x;
printf("Please enter an integer: ");
scanf("%d", &x);
printf("\nYou have entered:\n\n");
printNum(x);
return 0;
}
Here's what you need to do. Similar to what #simonc said, it's a good idea to convert the user input to a string, then loop through the characters. For each character, convert it into an int and then take that into the switch statement.
EDIT---------------------------
Here's a way with strictly using integers.
First find how many digits your integer has. You can do this by a method mentioned here.
Then do integer division starting from the largest power of 10 that divides the integer you have and divide the divisor by 10 until you reach 1. For example:
If user input is 213, it has 3 digits. We divide this by 100 first.
213/100 = 2
We take the 2 and put it into the switch statement, outputting 2. Now we're done with the hundreds digit, so now we take the 13 from 213 and divide it by 10.
13/10 = 1 So now we output one.
Keep doing this process until you get to the ones digit.
Does this make sense?