c++ Converting roman numerals to decimals - c++

This program is a part of an exam I just took, that I had to write. I only got this far and couldn't get anywhere. Here is the prompt:"Write a Test Function toDecimal() that converts a roman numeral such as MMLXVII to it's decimal number representation. Use Main() to test the function. The toDecimal() function should have 2 arguments, the string array of roman numerals and a helper function. This helper function will return the numeric value of each of the letters used in roman numbers. Then convert the string arguments as so: Look at the first two characters,if the first is larger, convert the first and add it to the summation, then call the conversion function again with the second value and add both. IF the first character is lesser than the second subtract the first from the second, and add the result to the conversion of the string. without validation it will also convert strings like "IC". VAlidate the string arguement, if there is an error, call the error processing function. Provide at least two error processing functions and test toDecimal() with each. One could be adking the user to correct, the other may correct it."
I,X,C,M cannot be repeated more than 3 times in succession, D,L,V, can never be repeated in succession.I can only be subtracted from V and X,X can only be subtracted from L and C, C can only be subtracted from D and M. V, L, and D can never be subtracted.
I've lost about 2 days worth of sleep on this, tried writing it hundreds of different ways using and breaking the rules. This is the closest I've got on it.
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <cstring>
using namespace std;
bool checker(string roman);
// Adds each value of the roman numeral together
int toDecimal(string, bool* (*function)(string));
int convert(string roman, int i);
int main(){
string roman;
cout << "This program takes a roman numeral the user enters then converts it to decimal notation." << endl;
cout << "Enter a roman numeral: ";
cin >> roman;
transform(roman.begin(), roman.end(), roman.begin(), toupper);
cout << roman << " is equal to " << toDecimal(roman, *checker(roman)) << endl;
}
bool checker(string roman){
int length = roman.length();
for (int count = 0; count < length; count++){
string sub = roman.substr(count, count);
if(sub != "I" || sub != "V" || sub != "X" || sub != "L" || sub != "C" || sub != "D" || sub != "M"){
cout << "Error. Try Again"<< endl;
return false;
}
else if(convert(roman, count) == convert(roman, count-1) && convert(roman, count) == convert(roman, count+1)){
if (convert(roman,count) == 1 || convert(roman,count) == 10 || convert(roman,count) == 100 || convert(roman,count) == 1000)
if(convert(roman, count-1) == convert(roman, count-2) || convert(roman, count+1) == convert(roman, count+2)){
cout << "Error Try again" << endl;
return false;
}
else if (convert(roman,count) == 5 || convert(roman,count) == 50 || convert(roman,count) == 500){
cout << "Error Try again" << endl;
return false;
}
else return true;
}
}
return true;
}
int toDecimal(string s, bool*(checker) (string roman)){
/**map<char, int> roman;
roman['M'] = 1000;
roman['D'] = 500;
roman['C'] = 100;
roman['L'] = 50;
roman['X'] = 10;
roman['V'] = 5;
roman['I'] = 1;*/
checker(s);
int res = 0;
for (int i = 0; i < s.length() - 1; ++i){
int num = convert(s,i);
res += num;
/**if (roman[s[i]] < roman[s[i+1]])
res -= roman[s[i]];
else
res += roman[s[i]];
}
res += roman[s[s.size()-1]];*/}
return res;
}
int convert(string roman, int i){
enum romans {I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000};
int num = 0;
char c = roman[0];
switch(c){
case 'M':
num = M; break;
case 'D':
if(i + 1 != roman.size() && roman[i+1] == 'M'){
num = M - D;break;
}
else
num = D; break;
case 'C':
if(i + 1 != roman.size() && roman[i+1] == 'M' || roman[i+1] == 'D'){
if(roman[i+1] == 'M') num = M - C; break;
if(roman[i+1] == 'D') num = D - C; break;
}
else
num = C; break;
case 'L':
if(i + 1 != roman.size() && roman[i+1] == 'M' || roman[i+1] == 'D' || roman[i+1] == 'C'){
if(roman[i+1] == 'M') num = M - L; break;
if(roman[i+1] == 'D') num = D - L; break;
if(roman[i+1] == 'C') num = C - L; break;
}
else
num = L; break;
case 'X':
if(i + 1 != roman.size() && roman[i+1] == 'M' || roman[i+1] == 'D' || roman[i+1] == 'C'|| roman[i+1] == 'L'){
if(roman[i+1] == 'M') num = M - X; break;
if(roman[i+1] == 'D') num = D - X; break;
if(roman[i+1] == 'C') num = C - X; break;
if(roman[i+1] == 'L') num = C - X; break;
}
num = X; break;
case 'V':
if(i + 1 != roman.size() && roman[i+1] == 'M' || roman[i+1] == 'D' || roman[i+1] == 'C'|| roman[i+1] == 'L' || roman[i+1] == 'X'){
if(roman[i+1] == 'M') num = M - V; break;
if(roman[i+1] == 'D') num = D - V; break;
if(roman[i+1] == 'C') num = C - V; break;
if(roman[i+1] == 'L') num = L - V; break;
if(roman[i+1] == 'X') num = X - V; break;
}
num = V; break;
case 'I':
if ( i + 1 != roman.size() && roman[i + 1] != 'I'){
if(roman[i+1] == 'M') num = M - I; break;
if(roman[i+1] == 'D') num = D - I; break;
if(roman[i+1] == 'C') num = C - I; break;
if(roman[i+1] == 'L') num = L - I; break;
if(roman[i+1] == 'X') num = X - I; break;
}
num =1; break;
}
return num;
}
** I have added the help of people on here. This is an edit to show an progress/congress.

This is the code that I use to convert Roman (smaller than 3999) to Integer. You may check if it works for larger numbers.
int romanToInt(string s) {
map<char, int> roman;
roman['M'] = 1000;
roman['D'] = 500;
roman['C'] = 100;
roman['L'] = 50;
roman['X'] = 10;
roman['V'] = 5;
roman['I'] = 1;
int res = 0;
for (int i = 0; i < s.size() - 1; ++i)
{
if (roman[s[i]] < roman[s[i+1]])
res -= roman[s[i]];
else
res += roman[s[i]];
}
res += roman[s[s.size()-1]];
return res;
}
Hope this could help you.

The solution provided by Annie Kim works, but it uses a std::map, querying it several times for the same character, and I fail to see a reason for it.
int convert_roman_digit(char d)
{
switch (d)
{
case 'M': return 1000;
case 'D': return 500;
case 'C': return 100;
case 'L': return 50;
case 'X': return 10;
case 'V': return 5;
case 'I': return 1;
default: throw std::invalid_argument("Invalid digit");
}
}
int roman_to_int(const std::string& roman)
{
int result = 0, last_added = 0;
for (auto it = roman.rbegin(); it != roman.rend(); ++it)
{
const int value = convert_roman_digit(*it);
if (value >= last_added)
{
result += value;
last_added = value;
}
else
{
result -= value;
}
}
return result;
}
Caveat: the function happily accepts some invalid inputs (e.g. IMM) including "negative" numbers (e.g. IIIIIIIIIIIIIX), there are no overflow checks, and it throws. Feel free to improve it.

int romanToInt(string s)
{
unordered_map<char, int> roman;
roman['I'] = 1;
roman['V'] = 5;
roman['X'] = 10;
roman['L'] = 50;
roman['C'] = 100;
roman['D'] = 500;
roman['M'] = 1000;
int num = 0, prev = 0, curr;
for (int i = s.length() - 1; i >= 0; i--)
{
curr = roman[s[i]];
num += (curr >= prev ? 1 : -1) * curr;
prev = curr;
}
return num;
}

Related

string subscript out of range in C++ for Cowculations

Please help with debugging.
It gives me an error 'string subscript out of range error' after the fifth input.
I was unable to figure out what to change.
Here is the code:
#include <iostream>
#include <string>
#define N 100
int str2int(std::string input)
{
int num = 0;
for (int i = 0; i < input.length(); i++)
{
if (input[i] == 'V')
num *= 4 + 0;
else if (input[i] == 'U')
num *= 4 + 1;
else if (input[i] == 'C')
num *= 4 + 2;
else if (input[i] == 'D')
num *= 4 + 3;
}
return num;
}
int main(void)
{
int tablet = 0, num1 = 0, num2 = 0, ans = 0;
std::string cowNum1 = "", cowNum2 = "", result = "";
std::string operation = "";
std::cin >> tablet;
std::cout << "COWCULATIONS OUTPUT" << std::endl;
while (tablet--)
{
std::cin >> cowNum1 >> cowNum2;
num1 = str2int(cowNum1);
num2= str2int(cowNum2);
for (int oprt = 0; oprt < 3; oprt++)
{
std::cin >> operation[oprt];
switch (operation[oprt])
{
case 'A':
{
num2 += num1;
break;
}
case 'R':
{
num2 >>= 2;
break;
}
case 'L':
{
num2 <<= 2;
break;
}
case 'N':
default:
break;
}
}
std::cin >> result;
ans = str2int(result);
if (num2 == ans)
std::cout << "YES" << std::endl;
else
std::cout << "NO" << std::endl;
std::cout << "END OF OUTPUT" << std::endl;
}
return 0;
}
Question is from 377 - Cowculations
Sample Input
5
VVVVU
VVVVU
A
A
A
VVVVVVUV
VVCCV
VVDCC
L
R
A
VVVVUCVC
VVCCV
VVDCC
R
L
A
VVVVUCVV
VVUUU
VVVVU
A
N
N
VVVVVUCU
DDDDD
VVVVU
A
L
L
UVVVVVVV
You may not use the subscript operator for an empty string to change its value
std::cin >> operation[oprt];
At least you have to declare the object operation with the magic number 3 used in your for loop. For example
std::string operation( 3, '\0' );
Or
std::string operation;
operation.resize( 3 );
If you need to enter only one characters in a loop then an object of the type std::string is not required. You could just write
for (int oprt = 0; oprt < 3; oprt++)
{
char c;
std::cin >> c;
switch ( c )
{
case 'A':
{
num2 += num1;
break;
}
case 'R':
{
num2 >>= 2;
break;
}
case 'L':
{
num2 <<= 2;
break;
}
case 'N':
default:
break;
}
}

previous greatest palindrome numbers before a given palindrome number

The Question is:
You are given a number 'N' in the form of a string 'S', which is a palindrome. You need to find the greatest number strictly less than 'N' which is also a palindrome.
I tried to solve this question but is giving wrong answer for some test cases. can anyone help me to correct my code.
Below is my code:
string nextSmallerPalindrome(string &s)
{
int n = s.length();
string ans = "";
if(n == 1)
{
s[0]--;
return s;
}
if(s == "11")
{
return "9";
}
// For Handling odd cases
if(n % 2 != 0)
{
int idx = n / 2;
int diff = 0;
if(s[idx] == '0')
{
s[idx] = '9';
diff = 1;
}
else
{
s[idx]--;
}
idx--;
while(idx >= 0 && diff == 1)
{
if(s[idx] == '0')
{
s[idx] = '9';
idx--;
}
else
{
s[idx]--;
diff = 0;
break;
}
}
int i = 0;
while(i < n && s[i] == '0')
{
i++;
}
for(; i < n; i++)
{
ans = ans + s[i];
}
int new_n = ans.length();
int j = 0;
int k = new_n - 1;
while(j < k)
{
if(ans[j] == ans[k])
{
j++;
k--;
}
else
{
ans[k] = ans[j];
j++;
k--;
}
}
return ans;
}
else // For handling even cases
{
int idx = n / 2 - 1;
int diff = 0;
if(s[idx] == '0')
{
s[idx] = '9';
diff = 1;
}
else
{
s[idx]--;
}
idx--;
while(idx >= 0 && diff == 1)
{
if(s[idx] == '0')
{
s[idx] = '9';
idx--;
}
else
{
s[idx]--;
diff = 0;
break;
}
}
int i = 0;
while(i < n && s[i] == '0') // For ignoring Zeros from front of the string
{
i++;
}
for(; i < n; i++) //storing all the string s in new string ans after ignoring front 0
{
ans = ans + s[i];
}
int new_n = ans.length();
int j = 0;
int k = new_n - 1;
while(j < k) // checking and changing the last half into first half
{
if(ans[j] == ans[k])
{
j++;
k--;
}
else
{
ans[k] = ans[j];
j++;
k--;
}
}
return ans;
}
}
Input Format:
The first line of the input contains an integer T denoting the number of test cases.
The first and the only line of each test case contains a string 'S', denoting the number whose next smaller palindrome is to be found.
Test Case:
19
7
77
101
1001
1221
144441
3444444443
57855875
10000001
11
1
111
101
1001
11011
1110111
1190911
20002
10011001
Excuse me, but I will not fix the code. I will rather describe how I would solve it. If you like the idea, then you will have a very easy time doing it.
A palindrome has n digits. n may be pair or odd. The first n / 2 digits (rounded upwards) is a number. Get that number (cut down the digits in the second half) and subtract 1.
Look at the result and the number of its digits. If subtracting 1 decreases the number of digits of your half-number, then handle that accordingly. Should be easy if you have the right idea.
Seems like using the same expression for idx in even cases as odd cases works better.
(It still doesn't handle the case for 7, though.)
Change this:
else // For handling even cases
{
int idx = n / 2 - 1;
to this:
else // For handling even cases
{
int idx = n / 2;
Results:
here's a working code
#include <bits/stdc++.h>
string nextSmallerPalindrome(string &s) {
// Write your code here.
string ans = s ;
if(s=="11"){
return "9";
}
int c = 0 ;
if(s.size()%2==1){
int k = s.size()/2 ;
//string ans = s ;
while(k>=0){
if(k==0 && ans[k]=='1' && ans.size()>1){
// cout<<"hola\n";
ans = ans.substr(1,ans.size()-2);
ans=ans+'9';
break;
}
if(ans[k]-'0'!=0){
int temp = ans[k]-'0';
temp-= 1 ;
ans[k] = (temp) +'0';
ans[s.size()-1-k] = (temp) +'0';
return ans;
}
else{
ans[k] = (9) +'0';
ans[s.size()-1-k] = (9) +'0';
k--;
}
}
}
else{
int k = s.size()/2 ;
while(k>=0){
if(k==0 && ans[k]=='1' && ans.size()>1){
ans = ans.substr(1,ans.size()-2);
ans=ans+'9';
break;
}
if(ans[k]-'0'!=0){
int temp = ans[k]-'0';
temp-= 1 ;
ans[k] = (temp) +'0';
ans[s.size()-1-k] = (temp) +'0';
return ans ;
}
else{
ans[k] = (9) +'0';
ans[s.size()-1-k] = (9) +'0';
if(c==0){
c++;
k-=2;
}
else k--;
}
}
}
return ans ;
}

C++ Arabic numbers to Roman Numeral's & vice versa

I am writing a C++ program that converts between Arabic and Roman numbering systems. I wrote one program that converts Arabic to Roman and have another program that converts Roman to Arabic.
The problem is that I can't figure out how to merge them into one single program so that the user can input an Arabic or Roman number and as a result, the program would convert said number to the other.
My question is HOW can I merge these two programs into one?
Code for Roman to Arabic
#include <iostream>
using namespace std;
int main()
{
char roman_Numeral;
int arabic_Numeral = 0;
cout << "Enter the Roman Numeral in Capital letters (e.g. CCXIX) : ";
while (cin.get(roman_Numeral))
{
if (arabic_Numeral > 100)
{
cout << "\nInvalid Value. Number must be between I and C" << endl;
return 0;
}
else if (roman_Numeral == 'C')
{
roman_Numeral = cin.peek();
if (roman_Numeral == 'M' || roman_Numeral == 'D')
{
arabic_Numeral = arabic_Numeral - 100;
}
else
{
arabic_Numeral = arabic_Numeral + 100;
}
}
else if (roman_Numeral == 'L')
{
roman_Numeral = cin.peek();
if (roman_Numeral == 'M' || roman_Numeral == 'D'
|| roman_Numeral == 'C')
{
arabic_Numeral = arabic_Numeral - 50;
continue;
}
else
{
arabic_Numeral = arabic_Numeral + 50;
continue;
}
}
else if (roman_Numeral == 'X')
{
roman_Numeral = cin.peek();
if (roman_Numeral == 'M' || roman_Numeral == 'D'
|| roman_Numeral == 'C' || roman_Numeral == 'L')
{
arabic_Numeral = arabic_Numeral - 10;
continue;
}
else
{
arabic_Numeral = arabic_Numeral + 10;
continue;
}
}
else if (roman_Numeral == 'V')
{
roman_Numeral = cin.peek();
if (roman_Numeral == 'M' || roman_Numeral == 'D'
|| roman_Numeral == 'C' || roman_Numeral == 'L'
|| roman_Numeral == 'X')
{
arabic_Numeral = arabic_Numeral - 5;
continue;
}
else
{
arabic_Numeral = arabic_Numeral + 5;
continue;
}
}
else if (roman_Numeral == 'I')
{
roman_Numeral = cin.peek();
if (roman_Numeral == 'M' || roman_Numeral == 'D'
|| roman_Numeral == 'C' || roman_Numeral == 'L'
|| roman_Numeral == 'X' || roman_Numeral == 'V')
{
arabic_Numeral = arabic_Numeral - 1;
continue;
}
else
{
arabic_Numeral = arabic_Numeral + 1;
continue;
}
}
else
break;
}
cout << arabic_Numeral << endl;
return 0;
}
Code for Arabic to Roman
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
#define MAX_INPUT 100 // These constants hold high and low integer numbers,
#define MIN_INPUT 1
#define ARRAY_SIZE 4 // and the array size declarator.
string convert(int digit, string low, string mid, string high);
int main()
{
string answers[ARRAY_SIZE] = { "", "", "", "" }; //An array of string to hold the output from the convert function.
int accumulator = 0; // Variable to hold number of arabic numbers converted.
int userNum = 0;
string strUserNum;
do
{
cout << "";
cout << "Enter an arabic number between 1 and 100: ";
cin >> strUserNum;
userNum = std::stoi(strUserNum);
if (userNum == 0 || userNum > MAX_INPUT)
{
cout << "\nInvalid Value. Number must be between 1 and 100" << endl;
return 0;
}
else if (userNum == 'end')
{
cout << "Exiting program:";
break;
}
int thous = userNum / 1000;
int hund = userNum % 1000 / 100;
int tens = userNum % 100 / 10;
int ones = userNum % 10 / 1;
answers[0] = convert(thous, "M", "M", "M");
answers[1] = convert(hund, "C", "D", "M");
answers[2] = convert(tens, "X", "L", "C");
answers[3] = convert(ones, "I", "V", "X");
cout << answers[0] << answers[1] << answers[2];
cout << answers[3] << endl;
cout << endl;
break;
} while (userNum != 'end');
system("PAUSE");
return 0;
}
string convert(int digit, string low, string mid, string high)
{
if (digit == 1)
{
return low;
}
if (digit == 2)
{
return low + low;
}
if (digit == 3)
{
return low + low + low;
}
if (digit == 4)
{
return low + mid;
}
if (digit == 5)
{
return mid;
}
if (digit == 6)
{
return mid + low;
}
if (digit == 7)
{
return mid + low + low;
}
if (digit == 8)
{
return mid + low + low + low;
}
if (digit == 9)
{
return low + high;
}
if (digit == 0)
{
return "";
}
}
Put code (that inside the main block) for Roman to Arabic into void procedureRomanToArabic()
The same for Roman to Arabic. Put it into void procedureArabicToRoman().
Remove remove ArabicToRoman do-while and move it to main.
void procedureRomanToArabic(){
char roman_Numeral;
int arabic_Numeral = 0;
//...
cout << arabic_Numeral << endl;
}
void procedureArabicToRoman()
{
string answers[ARRAY_SIZE] = { "", "", "", "" }; //An array of string to hold the output from the convert function.
int accumulator = 0; // Variable to hold number of arabic numbers converted.
int userNum = 0;
string strUserNum;
//remove do while here
cout << "";
cout << "Enter an arabic number between 1 and 100: ";
cin >> strUserNum;
//...
answers[2] = convert(tens, "X", "L", "C");
answers[3] = convert(ones, "I", "V", "X");
cout << answers[0] << answers[1] << answers[2];
cout << answers[3] << endl;
cout << endl;
}
int main(){
char type;
do{
cout<<"2 for Arabic to Roman, 1 for Roman to Arabic, or anything else for exit";
cin>>type;
if(type=='1')
procedureArabicToRoman();
else if(type =='2')
procedureRomanToArabic();
else break; //end program
} while(true);
}

Aborting when trying to reading and writing bmp files c++

this is my first post in stackoverflow.
I write a program that should take a bmp file in input, and black and white it and then write it into the out.bmp.
when I started to write the code, i delete the bmp file format at the end of the name of input and then open it with text editor, then write the code, and the output style is like the input.
when I type ./a.out <in.bmp>out.bmp in terminal, I get an Abort error (Aborted (core dumped)) and when I give the ./a.out < in > out.bmp gimp say to me it is not a bmp file.
here is the code:
// In the Name of God
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <math.h>
#include <sstream>
using namespace std;
bool TypeIsTrue (string type){
if (type == "424d")
return true;
return false;
}
int GrayIt (int b , int g , int r){
return (b + g + r) / 3 ;
}
int ConvertToDec(string hex){
long int dec = 0;
reverse(hex.begin(), hex.end());
for (int i = 0 ; i <hex.size();i++){
if (hex[i] == 'a')
dec = dec + 10 *(pow(16,i));
else if (hex[i] == 'b')
dec = dec + 11 *(pow(16,i));
else if (hex[i] == 'c')
dec = dec + 12 *(pow(16,i));
else if (hex[i] == 'd')
dec = dec + 13 *(pow(16,i));
else if (hex[i] == 'e')
dec = dec + 14 *(pow(16,i));
else if (hex[i] == 'f')
dec = dec + 15 *(pow(16,i));
else
dec = dec + ((hex[i] - '0')*(pow(16,i)));
}
return dec;
}
string ConvertToHex(int dec){
string hex;
int reminded,Divided;
reminded = dec % 16 ;
Divided = dec / 16;
if (Divided == 10){
hex = "a";
}
else if (Divided == 11){
hex = "b";
}
else if (Divided == 12){
hex = "c";
}
else if (Divided == 13){
hex = "d";
}
else if (Divided == 14){
hex = "e";
}
else if (Divided == 15){
hex = "f";
}
else if (Divided == 0){
hex = "0";
}
else if (Divided == 1){
hex = "1";
}
else if (Divided == 2){
hex = "2";
}
else if (Divided == 3){
hex = "3";
}
else if (Divided == 4){
hex = "4";
}
else if (Divided == 5){
hex = "5";
}
else if (Divided == 6){
hex = "6";
}
else if (Divided == 7){
hex = "7";
}
else if (Divided == 8){
hex = "8";
}
else if (Divided == 9){
hex = "9";
}
if (reminded == 10){
hex = hex+"a";
}
else if (reminded == 11){
hex = hex+"b";
}
else if (reminded == 12){
hex = hex+"c";
}
else if (reminded == 13){
hex = hex+"d";
}
else if (reminded == 14){
hex = hex+"e";
}
else if (reminded == 15){
hex = hex+"f";
}
else if (reminded == 0){
hex = hex+"0";
}
else if (reminded == 1){
hex = hex+"1";
}
else if (reminded == 2){
hex = hex+"2";
}
else if (reminded == 3){
hex = hex+"3";
}
else if (reminded == 4){
hex = hex+"4";
}
else if (reminded == 5){
hex = hex+"5";
}
else if (reminded == 6){
hex = hex+"6";
}
else if (reminded == 7){
hex = hex+"7";
}
else if (reminded == 8){
hex = hex+"8";
}
else if (reminded == 9){
hex = hex+"9";
}
return hex;
}
int main (){
vector <string> a;
vector <string> r;
vector <string> g;
vector <string> b;
vector <string> out;
string temp;
int red,green,blue;
while(cin >> temp){
a.push_back (temp);
}
if(!TypeIsTrue(a[0])){
cout<<"The file is not bmp\nRerun program"<<endl;
abort();
}
int phase = 1;
for (int i = 27 ; i < a.size(); i++){ //int i = 27
string first;
string last;
first = a[i].substr(0,2);
last = a[i].substr(2,3);
if(phase == 4)
phase = 1;
if(phase == 1){
b.push_back(first);
g.push_back(last);
phase ++;
// cout<<"push_backed"<<endl;
}
else if(phase == 2){
r.push_back(first);
b.push_back(last);
phase ++;
// cout<<"push_backed"<<endl;
}
else if(phase == 3){
g.push_back(first);
r.push_back(last);
phase ++;
// cout<<"push_backed"<<endl;
}
}
for (int i = 0 ; i <27 ; i++){
out.push_back(a[i]);
}
for(int i = 27 ; i<b.size() ; i++){
blue = ConvertToDec(b[i]);
green = ConvertToDec(g[i]);
red = ConvertToDec(r[i]);
out.push_back ( ConvertToHex( GrayIt (blue , green , red)));
out.push_back ( ConvertToHex( GrayIt (blue , green , red)));
out.push_back ( ConvertToHex( GrayIt (blue , green , red)));
}
int j = 1 ;
for (int i = 0 ; i < 27 ; i++){
cout<< out[i] << " ";
if (j == 8){
cout<<endl;
j = 0;
}
j++;
}
j=1;
bool space = false;
for (int i = 27 ; i < out.size(); i++){
if( i == 27 + 10){
cout<<endl;
j = 1;
}
cout<<out[i];
if (space)
cout<<" ";
j++;
if(j == 17){
cout<<endl;
j = 1 ;
}
space=!space;
}
return 0;
}
You're getting an abort error because you asked for one.
if(!TypeIsTrue(a[0])){
cout<<"The file is not bmp\nRerun program"<<endl;
abort();
}
If your program is designed to have its output redirected, it is very important to send error messages to stderr (and std::cerr or std::clog) and not stdout.
BTW, the type test is failing because BMP files are not text, it makes no sense to read them using cin >> variable.
In addition, there's no guarantee that a[0] even exists. You need to test a.size() first.
if(a.size() < 1 || !TypeIsTrue(a[0])){
cerr << "The file is not bmp\nRerun program\n";
abort();
}

How do I add a character to a string after each iteration of a loop c++

I'm trying to create a roman calculator that reads from a file. I'm struggling to figure out how to add characters to a string. I would like a new character to be added with no spaces after each iteration of a loop this would be used when the program is writing the answer.
I've tried this.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
string convert_to_Roman(int num)
{
string c;
while (num>0)
{
string c;
if (num >= 1000)
{
num = num - 1000;
return c='M';
}
else if (num >= 500 && num<1000)
{
num = num -500;
return c = 'D';
}
else if (num >= 100 && num<500)
{
num = num -100;
return c= 'C';
}
else if (num >= 50 && num<100)
{
num = num - 50;
return c = 'L';
}
else if (num >= 10 && num<50)
{
num = num - 10;
return c = 'X';
}
else if (num >= 5 && num<10)
{
num = num - 5;
return c = 'V';
}
else if (num<5)
{
num = num - 1;
return c = 'I';
}
c +=c;
//cout<<"answer= "<< + answer<<endl;
}
cout << c;
}
int convert_from_Roman(string & s)
{
int num=0;
int length; //length of string
length = s.length();
for (int i = 0; i < length; i++)
{
char c = s[i];
int digit;
if (c == 'M')
{
return num = 1000;
}
else if (c == 'D')
{
return num = 500;
}
else if (c == 'C')
{
return num = 100;
}
else if (c == 'L')
{
return num = 50;
}
else if (c == 'X')
{
return num = 10;
}
else if (c == 'V')
{
return num = 5;
}
else if (c == 'I')
{
return num = 1;
}
else
{
cout << "invalid entry" << endl;
continue;
}
num += num;
}
cout<<num<<endl;
}
void print_Result(/* figure out the calling sequence */)
{
// fill in your code
}
// Note the call by reference parameters:
string finalAnswer()
{
string operand1, operand2;
char oper;
cout << "enter operation: " << endl;
cin >> operand1 >> operand2 >> oper;
int value1, value2, answer;
value1 = convert_from_Roman(operand1);
value2 = convert_from_Roman(operand2);
switch (oper)
{
case '+':
{
answer = value1 + value2;
break;
}
case '-':
{
answer = value1 - value2;
break;
}
case '*':
{
answer = value1*value2;
break;
}
case '/':
{
answer = value1 / value2;
break;
}
default:
{
cout << "bad operator : " << oper << endl;
return;
}
string answerInRoman = convert_to_Roman(answer);
return answerInRoman;
cout << "answer= " << answerInRoman << " (" << answer << ") " << endl;
}
You can simply use concatenation like so.
char addThis;
string toThis;
addThis = 'I';
toThis = "V";
toThis += addThis;
or
toThis = toThis + addThis;
If you want to place the number somewhere other than the end of a string, you can access the elements of a string like an array toThis[0] is equal to 'V'.
If you are not using std::string as mentioned below, this can be done with a dynamic character array and an insert method that resizes the array properly as follows:
#include <iostream>
using namespace std;
void addCharToArray(char * & array, int physicalSize, int & logicalSize, char addThis)
{
char * tempPtr;
if (physicalSize == logicalSize)
{
tempPtr = new char[logicalSize + physicalSize];
for (int i = 0; i < logicalSize; i++)
{
tempPtr[i] = array[i];
}
delete [] array;
array = tempPtr;
}
array[logicalSize] = addThis;
logicalSize++;
}
int main()
{
char addThis = 'I';
char * toThis;
int physicalSize = 1;
int logicalSize = 0;
toThis = new char[physicalSize];
toThis[0] = 'V';
logicalSize++;
//when adding into the array, you must perform a check to see if you must add memory
addCharToArray(toThis, physicalSize, logicalSize, addThis);
for (int i = 0; i < logicalSize; i++)
{
cout << toThis[i];
}
cout << endl;
return 0;
}