string subscript out of range in C++ for Cowculations - c++

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;
}
}

Related

invalid types 'int[int]' for array subscript in multidimensional array c++

While doing my course project of card game, i got this error
Invalid types `int[int]' for array subscript'
Here is the code :
#include <iostream>
#include <stdlib.h>
#include <time.h>
int randomize(int, int);
int* generateCardNumber(int[5]);
int* generateCardLogo(int, int[13][4], int[5]);
int* compareCard(int[5], int[5], int[5], int[5], int[13][4]);
int printResult(int[5]);
void showCard(int, int[5], int[5], int[5], int[5]);
void printCard(int[5], int[5]);
using namespace std;
int main()
{
srand(time(NULL));
int player1Number[5], player1Logo[5];
int *number1, *logo1;
int player2Number[5], player2Logo[5];
int *number2, *logo2;
int cardInfo[13][4];
int **card;
char answer;
do
{
int playerInput;
int d, c, r;
int player1Score, player2Score;
cout<<"Welcome to the card game!"<<endl;
cout<<" Choose player{1: Player 1; 2: Player 2} : ";
cin>>playerInput;
cout<<endl;
do
{
cout<<"Press d to deal card :";
}while(d != 'd');
number1 = generateCardNumber(player1Number);
logo1 = generateCardLogo(1,cardInfo, player1Number);
for (int i = 0; i<5; i++)
{
cardInfo[player1Number[i]][player1Logo[i]] = 1;
}
number2 = generateCardNumber(player2Number);
logo2 = generateCardLogo(2,cardInfo, player2Number);
for (int i = 0; i<5; i++)
{
cardInfo[player2Number[i]][player2Logo[i]] = 1;
}
showCard(playerInput,player1Number,player1Logo,
player2Number,player2Logo);
do
{
cout<<"Press c to compare card :";
}while(c != 'c');
*card = compareCard(player1Number,player1Logo,
player2Number,player2Logo,cardInfo);
for (int i = 0; i<5; i++)
{
if(cardInfo[player1Number[i]][player1Logo[i]] = -1)
{
player1Number[i] = -1;
player1Logo[i] = -1;
}
else if(cardInfo[player2Number[i]][player2Logo[i]] = -1)
{
player2Number[i] = -1;
player2Logo[i] = -1;
}
}
showCard(playerInput,player1Number,
player1Logo,player2Number,player2Logo);
do
{
cout<<"Press r to show result :";
}while(r != 'r');
if(playerInput == 1)
{
cout<<"Player1 (You): ";
player1Score = printResult(player1Number);
cout<<"Player2 (Computer): ";
player2Score = printResult(player2Number);
if(player1Score > player2Score) cout<<"You WIN!"<<endl;
else cout<<"Computer WIN!"<<endl;
}
else if(playerInput == 2)
{
cout<<"Player1 (Computer): ";
player1Score = printResult(player1Number);
cout<<"Player2 (You): ";
player2Score = printResult(player2Number);
if(player2Score > player1Score) cout<<"You WIN!"<<endl;
else cout<<"Computer WIN!"<<endl;
}
cout<<"Do you want to play again? (y/n)"<<endl;
cin>>answer;
}while(answer == 'Y' || answer == 'y');
}
int randomize (int x, int y)
{
return (rand()%y + x);
}
int* generateCardNumber (int numberArray[5])
{
int arrayStoring[13] = {0,0,0,0,0,0,0,0,0,0,0,0,0};
for (int i = 0; i<5; i++)
{
do
{
numberArray[i] = randomize(1,13);
}while (arrayStoring[numberArray[i]] == 1);
arrayStoring[numberArray[i]] = 1;
}
return numberArray;
}
int* generateCardLogo (int turn, int cardInfo[4][13], int player2Number[5])
{
int logoArray[5];
if(turn == 1)
{
for (int i = 0; i<5; i++)
{
logoArray[i] = randomize(1,4);
}
return logoArray;
}
else if(turn == 2)
{
for (int i = 0; i<5; i++)
{
do
{
logoArray[i] = randomize(1,4);
}while (cardInfo[player2Number[i]][logoArray[i]] == 1);
}
return logoArray;
}
}
int** compareCard(int player1Number, int player1Logo, int player2Number, int player2Logo, int cardInfo)
{
for(int i=0; i<5 ; i++)
{
for(int j=0; j<5 ; j++)
{
if(player1Number[i] == player2Number[j])
{
if(player1Logo[i] < player2Logo[j]) cardInfo[player1Number[i]][player1Logo[i]] = -1;
else if(player1Logo[i] > player2Logo[j]) cardInfo[player2Number[i]][player2Logo[i]] = -1;
break;
}
}
}
return cardInfo;
}
int printResult (int playerNumber)
{
int playerScore = 0;
for (int i = 0; i<5; i++)
{
if(playerNumber[i] == -1) break;
else if(playerNumber[i] == 0)
{
playerScore += 15;
cout<<"15 ";
}
else if(playerNumber[i] > 0 && playerNumber[i] < 10 )
{
playerScore += (playerNumber[i] + 1);
cout<< (playerNumber[i] + 1) <<" ";
}
else if(playerNumber[i] >= 10)
{
playerScore += 12;
cout<<"12 ";
}
if(i<4) cout<<"+ ";
else if(i==4)
{
cout<<"= "<<playerScore<<" points";
}
}
return playerScore;
}
void printCard (int numberArray[5], int logoArray[5])
{
for (int i = 0; i<5; i++)
{
switch(numberArray[i])
{
case -1 :
cout<<"<fold> ";
break;
case 0 :
cout<<"Ace ";
break;
case 1 :
cout<<"2 ";
break;
case 2 :
cout<<"3 ";
break;
case 3 :
cout<<"4 ";
break;
case 4 :
cout<<"5 ";
break;
case 5 :
cout<<"6 ";
break;
case 6 :
cout<<"7 ";
break;
case 7 :
cout<<"8 ";
break;
case 8 :
cout<<"9 ";
break;
case 9 :
cout<<"10 ";
break;
case 10 :
cout<<"Jack ";
break;
case 11 :
cout<<"Queen ";
break;
case 12 :
cout<<"King ";
break;
}
switch(logoArray[i])
{
case -1:
break;
case 0:
cout<<"Diamond ";
break;
case 1:
cout<<"Club ";
break;
case 2:
cout<<"Heart ";
break;
case 3:
cout<<"Spade ";
break;
}
}
}
void showCard (int playerInput, int player1Number, int player1Logo, int player2Number, int player2Logo)
{
if(playerInput == 1)
{
cout<<"Player1 (You):"<<endl;
printCard(player1Number, player1Logo);
cout<<"Player2 (Computer):"<<endl;
printCard(player2Number, player2Logo);
}
else if(playerInput == 2)
{
cout<<"Player1 (Computer):"<<endl;
printCard(player1Number, player1Logo);
cout<<"Player2 (You):"<<endl;
printCard(player2Number, player2Logo);
}
}
Honestly, i still newbie at programming. So i didn't know that i can't return a whole array from a function. After searching for clue, i found out that i can use pointer to return an array from function. When i try to fix the code, this error come out and i didn't know what i need to fix.
The error keep appearing when i try to use the array from the function parameter,such as this
if(player1Number[i] == player2Number[j])<br/>
from function
int** compareCard(int player1Number, int player1Logo, int player2Number,
int player2Logo, int cardInfo)
and onward.
Can someone help me figure this out? Correction to the code would be very appreciated. Thankyou very much! (Sorry if my english is bad)
You're declaring compareCard with a bunch of arrays (so int pointers) as parameters:
int* compareCard(int[5], int[5], int[5], int[5], int[13][4]);
Then, however, you're implementing it using integers (not pointers) as parameters:
int** compareCard(int player1Number, int player1Logo, int player2Number, int player2Logo, int cardInfo)
{
for(int i=0; i<5 ; i++)
You're also using them as arrays:
if(player1Logo[i] < player2Logo[j]) cardInfo[player1Number[i]][player1Logo[i]] = -1;
Also, the return type is wrong. You're declaring it as int*, but then implement it as int**. You have to ensure that the signature of your function matches. It looks like taking the signature of the declaration and applying it to the definition should fix this compile time error.
Does your compiler issue any warnings for these function declarations? If not, see if you can set it to be more strict with warnings. Getting the correct warnings for potential errors greatly increases debug efficiency.

Converting Roman Numerals to Int - Getting the Wrong Output - Why?

Here is my code. First, I want to say, I have been experimenting, so if you see unnecessary variables here and there, that's why. But the main part of my code is in the function decimal in my class romanType. When I input certain roman numerals, I am not getting the exact numbers I want and it might be in my logic somewhere in my if/else statements.
By the way, to show how I traverse the string - I do it by reverse traversing. I go from the very end of the string to the very beginning of the string, which I think is easier with roman numerals. By the way, I also made an enum type so I could compare the roman numerals seeing which one is lesser, which one is greater etc. Then I used a map to be able to compare the enum values with the char value.
So the problem: For instance, when I type in CCC, I get 290 instead of 300. If you know what is wrong in my logic, I would greatly appreciate that! Thank you.
Furthermore, I am quite new to programming and would greatly appreciate any stylistic tips or anything I can learn about classes etc that I missed in writing this code? Please let me know what is best. Thank you.
#include <iostream>
#include <string>
#include <map>
using namespace std;
class romanType {
string numeral;
int k;
public:
romanType();
void rnumeral (string b) {numeral = b;}
int decimal(string num, char b, int temp) {
num = "";
enum RomanNumerals {I, V, X, L, C, D, M };
map<char, RomanNumerals> m;
m['I'] = I;
m['V'] = V;
m['X'] = X;
m['L'] = L;
m['C'] = C;
m['D'] = D;
m['M'] = M;
RomanNumerals roman1;
RomanNumerals roman2;
cout << "Please type in your roman numeral:" ;
cin >> num;
for (int i =0; i <num.length()-1; i++){
}
for(long i = num.length()-1; i>=0; i--)
{
b = num[i];
if (islower(b)) b=toupper(b);
roman1 = m[num[i]];
roman2 = m[num[i-1]];
switch(b){
case 'I':
if(num[i] == num.length()-1){
temp += 1;
}
break;
case 'V':
if(roman1 > roman2){
temp += 4;
continue;
}
else {
temp += 5;
}
break;
case 'X':
if(roman1 > roman2){
temp += 9;
continue;
}
else {
temp += 10;
}
break;
case 'L' :
if(roman1 > roman2){
temp += 40;
continue;
}
else {
temp += 50;
}
break;
case 'C':
if(roman1 > roman2){
temp += 90;
continue;
}
else {
temp += 100;
}
break;
case 'D' :
if(roman1 > roman2){
temp += 400;
continue;
}
else {
temp += 500;
}
break;
case 'M':
if(roman1 > roman2){
temp += 900;
continue;
}
else {
temp += 1000;
}
break;
}
}
return temp;
}
};
romanType::romanType () {
numeral = "";
}
int main() {
string k = "";
char b = ' ';
int temp = 0;
romanType type;
type.rnumeral(k);
int c = type.decimal(k, b, temp);
cout << c;
return 0;
}
EDIT: _____________________________________________________________________________
I found the solution to my problem. Here is my new code:
#include <iostream>
#include <string>
#include <map>
using namespace std;
string acceptRN();
class romanType {
string numeral;
int temp2;
int l;
// VARIABLES
public:
romanType();
//DEFAULT CONSTRUCTOR
void getRnumeral (string b)
{
numeral = b;
}
//SETTER
void decimal(string num, int temp, char b) {
num = numeral;
enum RomanNumerals {I, V, X, L, C, D, M };
map<char, RomanNumerals> m;
m['I'] = I;
m['V'] = V;
m['X'] = X;
m['L'] = L;
m['C'] = C;
m['D'] = D;
m['M'] = M;
RomanNumerals roman1;
RomanNumerals roman2;
RomanNumerals roman3;
for(long i = num.length()-1; i>=0; i--)
{
b = num[i];
if (islower(b)) b=toupper(b);
roman1 = m[num[i]];
roman2 = m[num[i-1]];
roman3 = m[num[i+1]];
switch(b){
case 'I':
if( roman3 > roman1 && i != num.length()-1){
continue;
}
else {
temp += 1;
break;
}
case 'V':
if(roman1 > roman2 && i != 0){
temp += 4;
continue;
}
else {
temp += 5;
}
break;
case 'X':
if( roman3 > roman1 && i != num.length()-1)
continue;
if(roman1 > roman2 && i!= 0){
temp += 9;
continue;
}
else {
temp += 10;
}
break;
case 'L' :
if(roman1 > roman2 && i!= 0){
temp += 40;
continue;
}
else {
temp += 50;
}
break;
case 'C':
if( roman3 > roman1 && i != num.length()-1)
continue;
if(roman2 == X && i!= 0){
temp += 90;
continue;
}
else {
temp += 100;
}
break;
case 'D' :
if(roman2 == C && i!= 0){
temp += 400;
continue;
}
else {
temp += 500;
}
break;
case 'M':
if(roman2 == C && i!= 0){
temp += 900;
continue;
}
else {
temp += 1000;
}
break;
}
}
temp2 = temp;
}
void showDecimal() {
cout << "Here is your roman numeral in decimal format:";
cout << temp2 << " \n \n \n";
}
};
romanType::romanType () {
numeral = "";
}
int main() {
string k = acceptRN();
int m = 0;
char l= ' ';
romanType type;
type.getRnumeral(k);
type.decimal(k, m, l);
type.showDecimal();
return 0;
}
string acceptRN(){
string num = "";
cout << "Please type in your roman numeral:" ;
cin >> num;
return num;
}
When I done the stuff from my comment and tweaked your code a bit I got this:
//---------------------------------------------------------------------------
int roman_ix[256]={-1};
const int roman_val[]={ 1 , 5 ,10 ,50 ,100,500,1000,0};
const char roman_chr[]={'I','V','X','L','C','D', 'M',0};
//---------------------------------------------------------------------------
int roman2int(char *s)
{
int i,x=0,v=0,v0;
// init table (just once)
if (roman_ix[0]<0)
{
for (i=0;i<256;i++) roman_ix[i]=0;
for (i=0;roman_chr[i];i++) roman_ix[roman_chr[i]]=i;
}
// find end of string
for (i=0;s[i];i++);
// proccess string in reverse
for (i--;i>=0;i--)
{
v0=v; // remember last digit
v=roman_val[roman_ix[s[i]]]; // new digit
if (!v) break; // stop on non supported character
if (v0>v) x-=v; else x+=v; // add or sub
}
return x;
}
//---------------------------------------------------------------------------
I tested on these:
1776 1776 MDCCLXXVI
1954 1954 MCMLIV
1990 1990 MCMXC
2014 2014 MMXIV
300 300 CCC
first number is converted from string, second is what it should be and last is the roman string.
If 256 entry table is too big you can shrink it to range A-Z which is significantly smaller but that require one more substraction in the code. It can be also hardcoded to get rid of the initialization:
//---------------------------------------------------------------------------
int roman2int(char *s)
{
// init
int i,x=0,v=0,v0; // A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
const int val['Z'-'A'+1]={ 0, 0, 100, 500, 0, 0, 0, 0, 1, 0, 0, 50, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 10, 0, 0 };
// find end of string
for (i=0;s[i];i++);
// process string in reverse
for (i--;i>=0;i--)
{
if ((s[i]<'A')||(s[i]>'Z')) break; // stop on non supported character
v0=v; v=val[s[i]-'A'];
if (v0>v) x-=v; else x+=v;
}
return x;
}
//---------------------------------------------------------------------------
As I got rid of your temp and roman1,roman2 and the switch if/else conditions and the code worked from the first compilation ... I am assuming that you are doing something fishy with them (got lost in the if/else combinations missing some edge case).

How to rearrange a string equation?

I am required to develop a program to solve linear equations. The programs
reads first an integer n which is the number of equations.
Then the program reads n lines containing the equations.
For example, the input to the program is like:
3
2x1+3x2+4x3=16
1x1+2x2+1x3=8
3x1+1x2+2x3=13
Any operation should first convert every equation to
the proper form. The equation proper should have the following properties
Variables are ordered alphabetically from left to right:
3x2+2x1+4x3=16
Should be
2x1+3x2+4x3=16
Any variable should appear only once:
4x1+3x2-2x1+4x3=16
Should be
2x1+3x2+4x3=16
Only one constant term should appear in the equation and it should be
on the right hand side:
2x1+3x2+5+4x3-11=10
Should be
2x1+3x2+4x3=16
Coefficient when equals to one or -1 the digit 1 is optional:
1x1+3x2-1x3=10
Can be input as be
x1+3x2-x3=10
What I have done so far is as follows:
#include<iostream>
#include<string>
#include<sstream>
#include<cstdlib>
using namespace std;
int main() {
int n;
cin >> n;
string eqn[100];
//get eq from user
for (int i = 0; i < n; i++) {
cin >> eqn[i];
}
size_t s = 0;
size_t y = 0;
for (int i = 0; i < n; i++) {
for (int x = 1; x <= ((eqn[i].length() - ((eqn[i].length() - 3) / 4)) / 3); x++)
{
int counter = 0;
ostringstream ss;
ss << x;
string j = ss.str();
for (int t = 0; t < eqn[i].length(); t++) {
y = eqn[t].find("x" + j, y + 1);
if (y < eqn[i].length()) { counter++; }
}
for (int o = 1; o <= counter; o++) {
s = eqn[i].find("x" + j, s + 1);
string x1 = eqn[i].substr(s - 1, 3);
string x2 = x2 + x1;
cout << x1;
}
}
cout << endl;
}
int k; cin >> k;
return 0;
}
but things became over complicated, and I am not sure if that is the right approach..
Is there a better way to operate on a string equation other than find(), substr()?
How should I approach the problem?
I started with a Syntax Diagram to define (I wouldn't call it) a language:
Then I translated this into a hand-written parser.
parse-equation.cc:
#include <iostream>
#include <algorithm>
int parseDigit(const char *&la)
{
switch (*la) {
case '0': ++la; return 0;
case '1': ++la; return 1;
case '2': ++la; return 2;
case '3': ++la; return 3;
case '4': ++la; return 4;
case '5': ++la; return 5;
case '6': ++la; return 6;
case '7': ++la; return 7;
case '8': ++la; return 8;
case '9': ++la; return 9;
default: return -1; // ERROR!
}
}
int parseNumber(const char *&la)
{
int value = parseDigit(la);
if (value < 0) return -1; // ERROR!
for (;;) {
const int digit = parseDigit(la);
if (digit < 0) return value;
value *= 10; value += digit;
}
}
struct Term {
int coeff; // -1 ... missing
int expon; // -1 ... missing -> ERROR
Term(int coeff = -1, int expon = 0): coeff(coeff), expon(expon) { }
};
Term parseTerm(const char *&la)
{
Term term;
term.coeff = parseNumber(la);
if (*la == 'x') {
++la;
term.expon = parseDigit(la);
if (term.coeff < 0) term.coeff = 1; // tolerate missing coeff. for x
}
return term;
}
struct Expression {
bool error;
int coeffs[10];
Expression(bool error = false): error(error)
{
std::fill(std::begin(coeffs), std::end(coeffs), 0);
}
};
Expression parseExpression(const char *&la)
{
Expression expr;
int sign = +1;
do {
const Term term = parseTerm(la);
if (term.expon < 0) return Expression(true); // ERROR!
expr.coeffs[term.expon] += sign * term.coeff;
switch (*la) {
case '+': sign = +1; ++la; break;
case '-': sign = -1; ++la; break;
case '=': break;
default: return Expression(true); // ERROR!
}
} while (*la != '=');
++la;
// parse right hand side
const int result = parseNumber(la);
if (result < 0) return Expression(true); // ERROR!
expr.coeffs[0] -= result;
// check for extra chars
switch (*la) {
case '\n': ++la;
case '\0': break;
default: return Expression(true); // ERROR!
}
return expr;
}
std::ostream& operator<<(std::ostream &out, const Expression &expr)
{
if (expr.error) out << "ERROR!";
else {
bool empty = true;
for (size_t i = 9; i; --i) {
const int coeff = expr.coeffs[i];
if (coeff) out << coeff << 'x' << i << std::showpos, empty = false;
}
if (empty) out << 0;
out << std::noshowpos << '=' << -expr.coeffs[0];
}
return out;
}
int main()
{
const char *samples[] = {
"2x1+3x2+4x3=16",
"1x1+2x2+1x3=8",
"3x1+1x2+2x3=13",
"2x1+3x2+5+4x3-11=10",
"x1+3x2-x3=10"
};
enum { nSamples = sizeof samples / sizeof *samples };
for (size_t i = 0; i < nSamples; ++i) {
std::cout << "Parse '" << samples[i] << "'\n";
const char *la = samples[i];
std::cout << "Got " << parseExpression(la) << std::endl;
}
return 0;
}
Compiled with g++ and tested in cygwin:
$ g++ -std=c++11 -o parse-equation parse-equation.cc
$ ./parse-equation
Parse '2x1+3x2+4x3=16'
Got 4x3+3x2+2x1=16
Parse '1x1+2x2+1x3=8'
Got 1x3+2x2+1x1=8
Parse '3x1+1x2+2x3=13'
Got 2x3+1x2+3x1=13
Parse '2x1+3x2+5+4x3-11=10'
Got 4x3+3x2+2x1=16
Parse 'x1+3x2-x3=10'
Got -1x3+3x2+1x1=10
$
Life Demo on Coliru
Note:
Instead of parseDigit() and parseNumber(), std::strtol() could be used. This would reduce the code significantly.
I used const char* for the "read head" la (... abbr. for "look ahead"). The pure C++ way might have been a std::stringstream or a std::string::iterator but, may be, I'm not used enough to these new fancy things. For me, the const char* was the most intuitive way...
The result on right hand side is simply subtracted from the coefficient for x0. So, either the right hand side is 0, or the negative coefficient for x0 becomes right hand side. For my pretty-printing operator<<(), I chose the latter option.
The error handling is rather poor and could be enhanced with more detailed infos about the reason of failed parsing. I left this out to not to "blow" the code even more.
The parser could be enhanced easily to skip white space at any appropriate place. This would improve the convenience.
In the current state, the result on right hand side might not be a negative number. I leave this extension as exercise.

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;
}

c++ Converting roman numerals to decimals

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;
}