Well, i made RGB To Hex Conversion. My programm in online compiler works pretty well, but on codewars it has a problem "control may reach end of non-void function". What should i do? Should I remove for loop?
using namespace std;
#include <iostream>
#include <string>
int checkForNumber(int input) {
if (input > 255) return 255;
if (input < 0) return 0;
else return input;
}
string check(int input) {
if (input < 10) return to_string(input);
switch (input)
{
case 10:
return "A";
break;
case 11:
return "B";
break;
case 12:
return "C";
break;
case 13:
return "D";
break;
case 14:
return "E";
break;
case 15:
return "F";
break;
}
}
**string YES(int input) {
string m;
char temp;
for (int i = 0; i < 2; i++) {
m += check(input % 16);
input /= 16;**
//problem is somewhere here
}
temp = m[0];
m[0] = m[1];
m[1] = temp;
return m;
}
int main()
{
string output;
ios_base::sync_with_stdio(false);
int r = 148 , g = 0, b = 211;
r = checkForNumber(r);
g = checkForNumber(g);
b = checkForNumber(b);
output += YES(r) + YES(g) + YES(b);
cout << output;
}
The problem is in your check(int input) function -- consider what happens if the value of the input argument is not in the range [10, 15]. I suggest putting in a default: case that returns something appropriate at the bottom of your switch block.
Related
I have a .txt file that contains:
XXXX:YYYY:ABCCCCE.
I need to write a function that reads this section of the .txt file ABCCCCE and finds the sum of the values of those characters.
Assume:
A = 1, B = 2, C = 3, D = 4, E = 5
Here is what I have so far to distinguish the values of each character:
int getComplexity(char theCode)
{
int complexity;
if(theCode == 'A')
{
complexity = 1;
} else if(theCode == 'B')
{
complexity = 2;
} else if(theCode == 'C')
{
complexity = 3;
} else if(theCode == 'D')
{
complexity = 4;
} else if(theCode == 'E')
{
complexity = 5;
}
return complexity;
}
I'm just not sure how I would read from the .txt file and convert the values. I am new to c++ so any help would be greatly appreciated!
I don't know if this is what your after but:
#include <fstream>
#include <numeric>
#include <vector>
using namespace std;
int Return_Complexity(char character)
{
switch (character)
{
case 'a':
return 1;
break;
case 'b':
return 2;
break;
case 'c':
return 3;
break;
case 'd':
return 4;
break;
case 'e':
return 5;
break;
default:
return 0; //Zero indicates that we didn't find what we're looking for
}
}
int main()
{
ifstream file{ "some-file.txt" };
vector<int> values;
char character;
while (file >> character)
{
int result = Return_Complexity(tolower(character));
if (result > 0) //if its a-e
values.push_back(result);
}
int Result = accumulate(values.begin(), values.end(), 1); //add them together
cout << Result;
}
this pushes back all characters found and then sums them up.
If this is not what your after, i will fix this.
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).
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i have a program and i should convert int to char into it
but i cant use itoa() because site's judge don't support it
so i wrote this:
xt[i]= rmn+'0';
but i get this error :
Runtime error: Illegal file open (/dev/tty)
How should i convert this?
My code is this : (for palsquare question of USACO)
/*
ID: sa.13781
PROG: palsquare
LANG: C++
*/
#include <iostream>
#include <fstream>
using namespace std;
ofstream fout("palsquare.out");
int tool(char xt[])//CORRECT
{
int p = 0;
while (xt[p] != 0)
p++;
return p;
}
void prt(char xt[])//CORRECT
{
int p = 0;
while (xt[p] != 0)
{
fout << xt[p];
p++;
}
}
void mabna(int a, char xt[], int mab)
{
int ex = 1, tavan = 0, rmn, n;
for (; ex <= a; ex *= mab)
tavan++;
for (int i = tavan - 1; a != 0; i--, a /= mab)
{
rmn = a % mab;
switch (rmn)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
xt[i] = rmn + '0';
break;
case 10:
xt[i] = 'A';
break;
case 11:
xt[i] = 'B';
break;
case 12:
xt[i] = 'C';
break;
case 13:
xt[i] = 'D';
break;
case 14:
xt[i] = 'E';
break;
case 15:
xt[i] = 'F';
break;
case 16:
xt[i] = 'G';
break;
case 17:
xt[i] = 'H';
break;
case 18:
xt[i] = 'I';
break;
case 19:
xt[i] = 'J';
break;
}
}
}
bool mirror(char *xt)//CORRECT
{
int p = 0;
int n = tool(xt);
for (int i = 0; i < (n / 2); i++)
if (xt[i] == xt[n - i - 1])
p++;
if (p == (n / 2))
return true;
return false;
}
void calc(int mab) //CORRECT
{
for (int i = 1; i <= 300; i++)
{
char p[10] = {0}, p2[10] = {0};
mabna(i * i, p2, mab);
if ( mirror(p2) == true )
{
mabna(i, p, mab);
prt(p);
fout << " ";
prt(p2);
fout << "\n";
}
}
}
int main()
{
ifstream fin("palsquare.in");
int mab;
fin >> mab;
calc(mab);
return 0;
}
Can you use sprintf()?
char s[16];
int x = 15;
sprintf(s, "%d", x);
If your int value is single digit, you can just cast it with (char)
If your int value is more than one digit, you can never expect a single char to hold it. char can only hold single character.
int num = 7;
char ch = (num + 48); //same effect as + '0'
cout << ch << endl;
OUTPUT: 7
If your int value is more than single digit. You need char* or char[] to hold the converted data. For example:
int num = 123987;
int len = 6;
int idx = len-1;;
char ch[20];
while(num > 0)
{
ch[idx] = (num%10) + 48;
num /= 10;
idx --;
}
for(int x=0; x<len; x++)
cout << "OUTPUT in char: " << ch[x];
OUTPUT in char: 123987
This is not a perfectly good way to handle this kind of situation, but it may gives you what you asked for.
Ok, so this program has been shortened to make it easier to read. There would obviously be more case statements to go along with the amount of variables there are. My question is why does my program get an error every time it runs. It is fine when it compiles but not when I run it.
#include <iostream>
#include <fstream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
string thearray[22960];
char bigfor[10];
int arrayvar = 0;
int finishedarray;
int a;
int b;
int c;
int d;
int e;
int f;
int g;
int h;
int i;
int j;
// Constants
int variable1 = 0;
int variable2 = 1;
int variable3 = 2;
int variable4 = 3;
int variable5 = 4;
int variable6 = 5;
int variable7 = 6;
int variable8 = 7;
int variable9 = 8;
int variable10 = 9;
for (a = 0; a < 36; a++)
{
switch (a)
{
case 0:
bigfor[variable1] = '0';
break;
case 1:
bigfor[variable1] = '1';
break;
case 2:
bigfor[variable1] = '2';
break;
case 3:
bigfor[variable1] = '3';
break;
case 4:
bigfor[variable1] = '4';
break;
case 5:
bigfor[variable1] = '5';
break;
case 6:
bigfor[variable1] = '6';
break;
case 7:
bigfor[variable1] = '7';
break;
case 8:
bigfor[variable1] = '8';
break;
case 9:
bigfor[variable1] = '9';
break;
}
thearray[arrayvar] = bigfor[variable1] + bigfor[variable2] + bigfor[variable4] +
bigfor[variable5] + bigfor[variable6] + bigfor[variable7] +
bigfor[variable8] + bigfor[variable9] + bigfor[variable10];
arrayvar = arrayvar + 1;
}
finishedarray = arrayvar + 1;
ofstream myfile;
myfile.open("codes.txt");
for (arrayvar = 0; a < finishedarray; a++)
{
myfile << thearray[arrayvar] << endl;
}
myfile.close();
return 0;
}
One problem is that you are reading uninitialized values here:
thearray[arrayvar] = bigfor[variable1]+ bigfor[variable2] + bigfor[variable4] +
bigfor[variable5] + bigfor[variable6] + bigfor[variable7] + bigfor[variable8] +
bigfor[variable9] + bigfor[variable10];
This is undefined behaviour. At this point in the program, only bigfor[variable1] is initialized.
Whatever you are trying to do, I have a feeling there is a simpler way to do it.
The problem was the addition you were doing. The addition will only add the integer-encoded values of the ASCII characters, and result in an integer. This will cause an error because you can't assign an integer to a std::string.
In addition to #juanchopanza's answer, your code can be improved substantially. For example, instead of listing out the indices manually, you can do this instead within your for loop:
std::string bigfor;
for (int a = 0; a < 36; ++a)
{
bigfor += (a + 48);
}
std::ofstream myfile("codes.txt");
for (int i = 0; i < bigfor.size(); ++i)
{
myfile << bigfor[i] << std::endl;
}