I dont know why this will not work, i need to swap the two chars enterd as a and b, it compiles but all the chars are replaced with the char inputted as b, any advise?
while (n != exist)
{
cout<<"What is the letter you want to swap?"<<endl;
cin>>a;
cout<<"What is the letter you want to swap it with?"<<endl;
cin>>b;
if (inFile.is_open())
{
while (inFile.good())
{
inFile.get(c);
if( c = a )
{
outFile<< b;
}
else if (c = b)
{
outFile<< a;
}
else
{
outFile<< c;
}
}
}
else
{
cout<<"Please run the decrypt."<<endl;
}
cout<<"Another letter? <n> to stop swapping"<<endl;
cin>>n;
}
In if and else if you need to use == instead of =. In C++/C you use == for comparison and = for assignment.
if( c == a )
{
outFile<< b;
}
else if (c == b)
{
outFile<< a;
}
= is for assignment, use == for comparison.
The way you have it, as long as a is not 0(the integer 0, not the character '0'), that first branch will always be executed.
if( c = a ) and else if (c = b) are suspect. You are assigning the value of a to c and the value of b to c, respectively. I believe if the assignment operation completes successfully (which is it), the block will execute. I believe you want the == operator, instead of the = operator.
You are assigning values instead of testing.
It should be
if (c == b)
and
if (c == a)
Related
The objective is to make it so that all uppercase letters are printed out in a string, however, I must keep the bool function and use it within my code. I have resolved some issues from the past but ran up with a issue that is preventing me from fixing it. Test cases are "HEllO" -> "HEO" "my" -> "" "NAME" -> "NAME" "Is" -> "I" "AnDeRsON" -> "ADRON".
#include <iostream>
using namespace std;
bool isUpperCase(char ch){
if(ch >= 'A' and ch <= 'Z'){
return true;
}
return false;
}
int main() {
string a = "";
cin >> a;
string c = "";
for(int i = 0; i < a.length(); i++)
{
if (isUpperCase(a[i])) i++;
{
c += a[i];
}
}
cout << c << endl;
}
Now whenever I do a case like "CHADnigeria" it turns it into "HDnigeria" even though I want it to say "CHAD". It also removes the capitals which I do not want and it should be removing the lowercases. "DancingInTheSky" turns into "ancingnheky" which should be "DITS". Reminder that the bool function must not be changed though.
I updated your program so that it works:
#include <iostream>
using namespace std;
bool isUpperCase(char ch){
if(ch >= 'A' and ch <= 'Z'){
return true;
}
return false;
}
int main() {
string a = "";
cin >> a;
string c = "";
for(int i = 0; i < a.length(); i++)
{
if (isUpperCase(a[i]))
{
c += a[i];
}
}
cout << c << endl;
}
What was your mistake: You put i++ after the if statement, which caused the weird output.
I hope I could help a little bit
It is a good programming praxis to write return condition; instead of if (condition) return true; else return false;. I would write your isUpperCase function just as:
bool isUpperCase(char ch) {
return (ch >= 'A' and ch <= 'Z');
}
The mistake you are looking for is in the main function, there is a i++ which is causing trouble. You wrote:
if (isUpperCase(a[i])) i++;
{
c += a[i];
}
And the compiler understands it as:
if (isUpperCase(a[i])) {
i++;
}
c += a[i];
Also, when you add a single character into a string in C++ i recommend you to use the push_back() method instead of the + operator. So c += a[i]; would be c.push_back(a[i]);. Both work fine, but push_back() is generally more efficient.
Help me plz..
I just had my midterm exam and one of the questions was to 'make your own function with three parameters that returns the smallest value.'
I coded for this in C++ as below.
int smallest(int a, int b, int c) {
if (a == b && b == c) {
return a;
}
else if ((a==b&&b!=c)||(b==c&&a!=b)||(a==c&&a!=b)){
if (a < b) { //a=c <b or a< b=c
return a;
}
else if (a < c) { //a=b <c or a< b=c
return a;
}
else if (b < a) { //b=c <a or b< a=c
return b;
}
else if (c < a) { //b=c <a or c< a=b
return c;
}
else {
cout << "Congratz you got -1 point";
return 99999999;
}
}
else {
if (a < b&&a < c) {
return a;
}
else if (b < a&&b < c) {
return b;
}
else {
return c;
}
}
When I run this in VS 2017, it works but..
if this function is called as
int main(){
cout << smallest(2,1,1);
return 0;
}
I thought this would make an error because there are two else if statements that include this case (else if(b < a) and else if(c < a)...)
It is not allowed for computers to choose which statement to run.. BUT WHY THIS WORKS..??? :( Pretty basic codes but I have no idea..
The two else if statements you mention are mutally exclusive in the sense that if the first condition evaluates to true, the second one is ignored. Ie:
if (a < b) {
return a;
}
else if (a < c) { // if this is true then...
return a;
}
else if (b < a) { // this condition wont even be evaluated
return b;
}
Also you seem to have a misunderstanding concerning return. Consider this code:
int foo() {
return 3;
return 5;
}
there is nothing wrong about this code, it just happens that the second return will never be executed.
Last but not least you should consider to simplify your code. Two if should be more than sufficient to produce the correct result. Something along the line of
if (a is smaller than b and smaller than c) return a;
else return the smaller of b and c;
The evaluation of the if statements happens from top to bottom. Therefore they don't need to be mutually exclusive, and the order of the conditionals does matter (cf. switch).
Note you can return the smallest value with the simple
return std::min({a, b, c});
I have a program where I want to update a variable from a string. The function will read in a string, find if it is addition, subtraction, etc. and then add it to the variable. The function is this:
using namespace std;
struct variable{
string name;
int value;
};
void update_varabile(string line, vector<variable> & v)
{
char c = line[0]; //variable to be updated
string b;
char d[0];
int flag = 0; //counter
int a = 0;
int temp_value = 0;
int perm_value = 0;
for (int i = 0; i < v.size(); i++) {
if (c == v[i].name[0]) {
flag = 1;
temp_value = v[i].value;
break;
}
}
if (flag == 1) { //variable is present
for (int i = 0; i< line.size(); i++) {
if (line[i] == '+'|| line[i] =='-'|| line[i] == '*'|| line[i] =='/') {
b[0] = line[i+1]; //assuming the integer is between 0 and 9
d[0] = b[0];
a = atoi (d);
if (line [i] == '+') {
perm_value = temp_value + a;
} else if (line [i] == '-') {
perm_value = temp_value - a;
} else if (line [i] == '*') {
perm_value = temp_value * a;
} else if (line [i] == '/') {
perm_value = temp_value / a;
}
}
}
for (int i = 0; i < v.size(); i++) {
if (v[i].name[0] == 'c') {
v[i].value = perm_value;
break;
}
}
}
}
The call in main looks like this:
int main()
{
variable a;
int val = 0;
string up = "c=c+2";
string f = "c";
vector<variable> q;
a.name = f;
a.value = val;
q.push_back(a);
update_varabile(up, q);
return 0;
}
However, when I run the code, I get this error message:
Assertion failed: ((m_->valid == LIFE_MUTEX) && (m_->busy > 0)), file C:/crossdev/src/winpthreads-git20141130/src/mutex.c, line 57
Process returned 1 (0x1) execution time : 0.014 s
Press any key to continue.
I have run the debugger line by line and it shows that the function properly executes. I have also tried to look for that C:/ file on my computer and it doesn't exist. Not sure why this isn't working.
First thing first, get rid of all the breaks. Only place breaks should be used in C++ is at the end of each case statement. Makes near impossible to read code with a bunch of breaks, because I have to go down and figure out what each break is there and why. If you need to get out of a for loop early, then use a while loop. you don't need breaks at the end of if and else statements because they cause the program to leave a function early, your if and else statements will naturally skip over if you are using if, else if, and else condition formatting.
Now having said that, you need to break down better what you are trying to do.
example you get a string value like this.
2+3+4-5+6
Your program is going to read from left to right. I am assuming you want it to take the first value which is two and then add three to it then four and so on and so fourth.
The way to do this is first parse the string for int values and then parse the addition and subtraction values. In other words read the int values out of the string untill you hit a value that is not between 0 and 9. Then see if that non-numerical value is an operator you are looking for. This way your program wont trip up on a value like 2555 and 2.
IE
//intValueHolder is a string.
while(i < line.size() && line[i] >= '0' && line[i] <= '9' ) {
intValueHolder.push_back(string[i]);
}
Then when you hit a '+' or something like that put the char value through a case statements. and don't forget to add a default value at the end to account for garbage input like 'a'. You may want to hold the value just incase you need to get your left side value first before you can get your right side value. But it sounded like you start out with a left side value so you really only need to find right and which operator it needs. I'm not going to rewrite your program because this looks like an assignment for school. But I will point you in the right direction. Let me know, if I was off on understanding your question.
You may also want to look into using queues for this, if you are not being restricted to just strings and vectors.
So I've been programming for an assignment -- I am supposed to create a program that asks for the number of questions, the correct answers, and the answers provided to score the test.In the program I wrote, I always get the same return value for the score: 4199676
Can anyone tell me why I get this return value? Many thanks.
int main(){
int qnum = 1;
int counter;
int corr_counter;
char correct[10000];
char answer[10000];
while(qnum != 0){
cout<<"Enter the number of questions on the test (0 to exit).\n";
cin>>qnum;
while(qnum < 0){
cout<<"Please enter a valid number of questions.\n";
cin>>qnum;
}
for(counter = 0; counter < qnum; counter++){
cout<<"Enter the correct answer for question "<<counter<<". The answer can be A, B, C, D, or E.\n";
cin>>correct[counter];
toupper(correct[counter]);
while(correct[counter] != 'A' && correct[counter] != 'B' && correct[counter] != 'C' && correct[counter] != 'D' && correct[counter] != 'E'){
cout<<"Please enter either A, B, C, D, or E.\n";
cin>>correct[counter];
toupper(correct[counter]);
}
}
for(counter = 0; counter < qnum; counter++){
cout<<"Enter the student's answer for question "<<counter<<". The answer can be A, B, C, D, or E.\n";
cin>>answer[counter];
toupper(answer[counter]);
while(answer[counter] != 'A' && answer[counter] != 'B' && answer[counter] != 'C' && answer[counter] != 'D' && answer[counter] != 'E'){
cout<<"Please enter either A, B, C, D, or E.\n";
cin>>answer[counter];
toupper(answer[counter]);
}
}
for(counter = 0; counter < qnum; counter++){
if(answer[counter] == correct[counter]){
corr_counter++;
}
}
cout<<"Score: "<<corr_counter<<"\n";
return(0);
}
}
You haven't initialised corr_counter.
You declare it at the top but you never initialised it to 0, which is what you meant to do. You are thus incrementing from an unknown start point.
I'm a usual lurker but this is my first post! I understand you guys like detail so I will do my best. I will appreciate whatever input anyone has.
I am working on an overloading the extraction operator for an object with a dynamic array of digits. The console input will have leading white space, then an int, then anything after. I need to ignore white space, extract the int, and then leave the rest alone. Easy right?
Here is an example of code I found online:
istream & operator >> (istream &m, MyInt & p)
{
int x = 0;
p.currentLength = 0;
while ((m.peek() == '\n') || (m.peek() == '\0') ||
(m.peek() == '\t') || (m.peek() == ' '))
{
m.get();
}
while ((m.peek() >= '0') && (m.peek() <= '9'))
{
if (p.currentLength >= p.maxSize)
{
p.grow();
}
m >> p.theNumber[x];
x++;
p.currentLength++;
}
m.get();
// reverse the order (i.e. - 123 to 321)
char * temp = new char[p.maxSize];
for (int y = 0; y < p.currentLength; y++)
{
temp[y] = p.theNumber[p.currentLength - 1 - y];
}
delete [] p.theNumber;
p.theNumber = temp;
return m;
}
Now, I understand this method may work, however to me, that seems like an extremmeelly inefficient method. For a trillion digit number, Grow() would reallocate the array a trillion times! Perhaps this is not as bad as I think it is?
My current method has been using seekg() and peek() and get(). Like so:
istream& operator >> (istream& is, MyInt& z)
{
int i = 0, j = 0;
// check if next char is white
while (is.peek() == 38)
{
j++;
is.seekg(j); // skip if white
}
while (isdigit(is.peek()))
{
i++;
is.seekg(j + i);
if (!is.peek())
{
is.clear();
break;
}
}
is.seekg(j);
z.length = i;
z.digits = new int[i + 1];
for (i = 0; i < z.length; i++)
{
z.digits[i] = C2I(is.get());
}
return is;
}
Also, here is my main:
int main()
{
MyInt B;
cout << "\n\nChange B to what num? ---> ";
cin >> B;
cout << "B is now: " << B;
char c;
cout << "\n\n\n\n\nEnter char to exit : ";
cin >> c;
return 0;
}
For the life of me I can not find what is causing my program to exit. The last output seems to say, 'B is now: -1'
I believe the this means the << B failed. I have B initialized to 0 currently, and the rest of my code has presented no other issues. It's private member data only include the pointer and a length (num of digits). Also C2I() is a function that converts '0' through '9' to 0 through 9.
A big issue for me is I am fairly new to parsing, so I don't have very eloquent ways to test this, or other ideas.
Again I appreciate everything you guys do. I have already learned a great deal from browsing here!