continue not working? [c++] - c++

Hi guys I've run into a problem,for some reason a blank string is being printed or you could also say nothing is being printed when I try to print out the string,this only occurs when I include a capital letter in the string such as acB if I type acb it sorts and prints them with no problems,I added a continue statement in to the for loop because I thought this would skip the rest of the code and go to the next iteration if that block of code got executed but to no avail anyway here is my code.
void order(char *str,int size){
bool sorted = false;
while(!sorted){
sorted = true;
for(int i = 0; i < size-1; i++){
if(str[i] >= 'A' && str[i] <= 'Z'){
if((str[i+1])-32 < str[i]){
char temp2 = str[i];
str[i] = str[i+1];
str[i+1] = temp2;
sorted = false;
continue;
}
}
if(str[i+1] < str[i]){
char temp = str[i];
str[i] = str[i+1];
str[i+1] = temp;
sorted = false;
}
}
}
}
int main()
{
char str[] = "aCb";
int size = sizeof(str) / sizeof(char);
order(str,size-1);
cout << str << endl;
}

void order(char *str,int size){
bool sorted = false;
while(!sorted){
sorted = true;
for(int i = 0; i < size - 1; i++){
if(str[i+1] >= 'A' && str[i+1] <= 'Z' && str[i] > 'Z'){
if(str[i+1] < str[i] - 32){
char temp2 = str[i];
str[i] = str[i+1];
str[i+1] = temp2;
sorted = false;
continue;
}
}
else{
if(str[i] >= 'A' && str[i] <= 'Z' && str[i + 1] >= 'Z'){
if(str[i+1] -32 < str[i]){
char temp2 = str[i];
str[i] = str[i+1];
str[i+1] = temp2;
sorted = false;
continue;
}
}
if(str[i+1] < str[i]){
char temp2 = str[i];
str[i] = str[i+1];
str[i+1] = temp2;
sorted = false;
continue;
}
}
}
}
}
int main()
{
char str[] = "aCB";
int size = sizeof(str) / sizeof(char);
order(str,size-1);
cout << str << endl;
}
First IF: Checks if the first letter is lowercase and the second letter is uppercase.
Second IF: Checks if the first letter is uppercase and the second letter is lowercase.
Third IF: then both letters are uppercase or lowercase.

Related

How to fill a string with chars in a for (or while) loop, c++ [duplicate]

This question already has answers here:
How to append a char to a std::string?
(14 answers)
Closed 3 years ago.
So, I've been writing a program that adds two Roman numbers and outputs the sum in Roman numbers as well. The issue I ran was and is, that the thing that checks the result is only reading the first output letter, not the entire output.
Which made me think about how to fill the string with chars (or strings with a length of one). I do something like:
#include <iostream>
int main() {
std::string str{" "};
for (int i = 0; i < 5; ++i) {
str[i] = 'A';
}
std::cout << str;
}
After running this, you get output "A", when I want it to be "AAAAA". I just really don't know how to make a list of chars dynamic one, if to say technical.
For context, here is the code for the Roman numerals. I tried doing this in Python, but it didn't work out well too, and since I initially started in C++, I want to know how to do such an operation there.
#include <iostream>
using namespace std;
// simple shit
// a func str gets a sum, then with while loops 'fills' the " " in the string s with some letters
string str(int sum) {
string s = " ";
int i = 0;
while (sum >= 1000) {
s[i] = 'M';
sum -= 1000;
++i;
}
while (sum >= 500) {
s[i] = 'D';
sum -= 500;
++i;
}
while (sum >= 100) {
s[i] = 'C';
sum -= 100;
++i;
}
while (sum >= 50) {
s[i] = 'L';
sum -= 50;
++i;
}
if (sum == 19) {
s[i] = 'X';
++i;
s[i] = 'I';
++i;
s[i] = 'X';
++i;
sum -= 19;
}
while (sum >= 10) {
s[i] = 'X';
++i;
}
if (sum == 19) {
s[i] = 'X';
++i;
s[i] = 'I';
++i;
s[i] = 'X';
++i;
sum -= 19;
}
if (sum == 9) {
s[i] = 'I';
++i;
s[i] = 'X';
++i;
sum -= 9;
}
while (sum >= 5) {
s[i] = 'V';
++i;
}
if (sum == 4) {
s[i] = 'I';
++i;
s[i] = 'V';
++i;
sum -= 4;
}
while (sum >= 1) {
s[i] = 'I';
++i;
}
for (int i = 0; i < s.length(); ++i) {
if (s[i] == ' ') {
s[i] = '\0';
}
}
//..and returns the string, full of " ", when I don't need those
return s;
}
//uh, that's the func to check if IX == 19, not 21. don't care about this one
int a(string prev) {
if (prev == "M") {
return 1000;
}
if (prev == "D") {
return 500;
}
if (prev == "C") {
return 100;
}
if (prev == "L") {
return 50;
}
if (prev == "X") {
return 10;
}
if (prev == "V") {
return 5;
}
if (prev == "I") {
return 1;
}
else {
return 0;
}
}
int main() {
//all the strings and other cool stuff
string s, letter, prev;
cin >> s;
int sum;
int prev_check;
int l = s.length();
// a loop to find a letter in a string we just input, and 'parse' it to the normal-digits (arabic) form
for (int i = 0; i < l; i++) {
letter = s[i];
if (letter == "M") {
sum += 1000;
//checking if nothing less than current Rome digit is behind it
if (i > 0) {
prev = s[i - 1];
prev_check = a(prev);
if (prev_check < 1000) {
sum -= prev_check * 2;
//you may be wondering, why times two?
//because I've already added the letter behind to my sum,
//so I have to substract it from sum twice
}
}
}
// fun fact - there cant exist numbers such as IM (999) in Rome letter, only C, X and V are "substractable"
//yet, I've still added this kinda "substraction" to all letters, just because I'm lazy to input specific ones for debugging my "substraction" func
if (letter == "D") {
sum += 500;
if (i > 0) {
prev = s[i - 1];
prev_check = a(prev);
if (prev_check < 500) {
sum -= prev_check * 2;
}
}
}
if (letter == "C") {
sum += 100;
if (i > 0) {
prev = s[i - 1];
prev_check = a(prev);
if (prev_check < 100) {
sum -= prev_check * 2;
}
}
}
if (letter == "L") {
sum += 50;
if (i > 0) {
prev = s[i - 1];
prev_check = a(prev);
if (prev_check < 50) {
sum -= prev_check * 2;
}
}
}
if (letter == "X") {
sum += 10;
if (i > 0) {
prev = s[i - 1];
prev_check = a(prev);
if (prev_check < 10) {
sum -= prev_check * 2;
}
}
}
if (letter == "V") {
sum += 5;
if (i > 0) {
prev = s[i - 1];
prev_check = a(prev);
if (prev_check < 5) {
sum -= prev_check * 2;
}
}
}
if (letter == "I") {
sum += 1;
}
}
//and... out
cout << str(sum);
}
It's quite some code, I know, I added a few comments explaining what am I doing here and there.
The below code might help to output 5 'A'
#include <iostream>
#include <vector>
int main() {
std::vector<char> val;
for (int i = 0; i < 5; ++i) {
val.push_back('A');
}
for (int a = 0; a < val.size(); ++a)
{
std::cout << val[a];
}
}

Error for c++ example

I want to input alphabet to binary code, and output the alphabet from generated binary code.
Example
1 --> a
01 --> b
001 --> c
0001 --> d
00001 --> e
000001 --> f
a => 1
b => 01
c => 001
d => 0001
e => 00001
-------------Encode.cpp--------------------
#include "Encode.h"
Encode::Encode()
{
}
Encode::~Encode()
{
}
void Encode::inputWord()
{
cout << "Input word: ";
cin.getline(word, 255);
return;
}// User input a word
char * Encode::getBuf(void)
{
return buffer;
}// return buffer to Decode::setBuf(char* buf)
void Encode::printEncResult()
{
int size = strlen(word);
int buffersize = 0;
cout << "Encoding result" << endl; // print similar binary
for (int i = 0; i < size; i++)
{
if (word[i] == 'z')
{
for (int j = 0; j < 25; j++)
{
cout<<buffer[buffersize++];
}
}
else
{
int len = (int)word[i] - (int)'a';
for (int j = 0; j < len; j++)
{
cout<<buffer[buffersize++];
}
cout << buffer[buffersize++];
}
}
}// output similar binary
int Encode::encodeWord(void)
{
int buffersize = 0;
int size = strlen(word);
for (int i = 0; i < size; i++)
{
if (word[i] == 'z')
{
for (int j = 0; j < 25; j++)
{
buffer[buffersize++] = '0';
}
}
else
{
int len = (int)word[i] - (int)'a';
for (int j = 0; j < len; j++)
{
buffer[buffersize++] = '0';
}
buffer[buffersize++] = '1';
}
}
return 0;
}// change word to similar binary
--------Decode.cpp-------------
#include "Decode.h"
Decode::Decode()
{
}
Decode::~Decode()
{
}
void Decode::setBuf(char * buf)
{
int i = 0;
int size = 0;
while (*(buf + i) == '1' || *(buf + i) == '0')
{
i++;
}
size = i;
for(int i = 0; i < size; i++)
{
buffer[i] = buf[i];
}
return;
}// set buffer from Encode::getBuf(void)
void Decode::printWord() // print similar binary
{
int i = 0;
int size = 0;
int check = 1;
while (check)
{
if (word[i] >= 'a' && (int)word[i] <= 'z')
{
i++;
size = i;
}
else
check = 0;
}
cout << "Decoding result" << endl;
for (int i = 0; i < size; i++)
{
if (word[i] >= 'a' && (int)word[i] <= 'z') // **this part is also strange** I can not shoten the code.
cout<<word[i];
}
cout << endl;
}
int Decode::decodebin(vector<char> buffer)
{
int buffersize = 0;
int check = 0;
int size = 0;
int i = 0;
char printval = 'a';
while (buffer[i] == '1' || buffer[i] == '0')
{
i++;
}
size = i;
for (int j = 0; j < size; j++) // nested loop does not work. I want save words in order
{
for (i = 0; i < size; i++)
{
if (buffer[i] == '0')
++printval;
else
{
word[j] = printval; // In this part, word[0] does not have any value.
printval = 'a';
}
}
}
return 0;
}
In this code, I want save values in order, but word[0] does not have any value. Moreover, If I input 'bb' then, 'bbbb' saved ins word array.
There are some problems and consideration you need to take care of:
as Fei Xiang said in the comments don't use magic numbers, use characters since you have a character array.
int printWord function you actually get the word and print the same word, there is no conversion as your problem statement. your didn't take buffer into account.
you are using some data validation to get your array size, this could end up a disaster(UB). you need to pass your array size to your function or use std::vector(Recommended).
in this statement if ((int)word[i] >= 97 || (int)word[i] <= 122) as I said don't use magic number and || should be change to && otherwise you end up in an infinity loop.
Anyway by keeping your approach(using array) and function signature here's what you can do :
int Decode::decodebin(void)
{
int buffersize = 0;
int check = 0;
int size = 0;
int i = 0;
char printval = 'a';
while(buffer[i] == '1' || buffer[i] == '0')
{
i++;
size = i;
}
for(int i = 0; i < size; i++)
{
if(buffer[i] == '0')
++printval;
else
{
cout << printval;
printval = 'a';
}
}
return 0;
}
void Decode::printWord()
{
int i = 0;
int size = 0;
int check = 1;
while(check)
{
if(word[i] >= 'a' && word[i] <= 'z')
{
i++;
size = i;
}
else
check = 0;
}
cout << "Decoding result" << endl;
for(int i = 0; i < size; i++)
{
int distance = word[i] - 'a';
for(int j = 0; j < distance; ++j)
cout << '0';
cout << '1';
}
cout << endl;
}
EDIT BASED ON OP REQUIREMENT IN COMMENTS:
using std::vector you can implement your needs like this :
#include <iostream>
#include <vector>
class Decode
{
public:
void decodebin(std::vector<char> buffer)
{
char printval = 'a';
for(unsigned int i = 0; i < buffer.size(); i++)
{
if(buffer[i] == '0')
++printval;
else
{
word.push_back(printval);
printval = 'a';
}
}
}
void printWord(void)
{
for(auto iter = word.begin(); iter != word.end(); ++iter)
std::cout << *iter;
std::cout << std::endl;
}
private:
std::vector<char> word;
};
int main()
{
Decode decoder;
std::vector<char> buffer = {'0', '1', '0', '0', '0', '0', '1', '0', '0', '0', '1'};
decoder.decodebin(buffer);
decoder.printWord();
return 0;
}
Here decodebin stores the given input into word member variable of Decode class. Then printWord function print word values on the screen.
std::vector has all the power of C-style array and it's nicer and easier to use. You can retrieve it's size whenever you want and you don't have to worry about the memory it's allocating.

whenever I try to run this code the break appears or stops working

what I want to do is :
Input a sentence from the user. Use full stop, space and comma as word separators. Each word should be stored in a 2D array whose columns vary in size and each row stores one word as a NULL terminated string.
For example, if the user inputs:
Hello how are you?
It should be stored as:
H E l l o NULL
h o w NULL
a r e NULL
y o u ? NULL
so whenever I try to run my code either this error appears
Exception thrown at 0x00832605 in Project109.exe: 0xC0000005: Access violation writing location 0xFDFDFE03.
or the program stops working.major problem is in
ptr[i][j] = str1[j];
`
char str1[20];
cin.get(str1, 20);
int len, sum = 0;
len = strlen(str1);
int i = 0;
while (str1[i] != '\0')
{
if (str1[i] == ' ' || str1[i] == '.' || str1[i] == ',' || str1[i] == '?' || str1[i] == ';')
{
sum = sum + 1;
}
i++;
}
char **ptr;
ptr = new char*[sum];
for (int i = 0; i < sum; i++)
{
ptr[i] = new char[20];
}
for (int i = 0; i < sum; i++)
{
for (int j = 0; j < 20; j++)
{
ptr[i][j] = '\0';
}}
for (int i = 0; i < sum; i++)
{
for (int j = 0; j < 20; j++)
{
if (str1[j] == ' ' || str1[j] == '.' || str1[j] == ',' || str1[j] == '?' || str1[j] == ';')
{
i++;
}
else
{
ptr[i][j] = str1[j];
}
}
}
for (int i = 0; i < sum; i++)
{
int j = 0;
while (ptr[i][j] != '\0')
{
cout << ptr[i][j];
j++;
}
}
for (int i = 0; i < sum; i++)
{
delete[] ptr[i];
}
delete[] ptr;
system("pause");
return 0;}
`
You are indexing out of range, and hitting memory with fence bytes containing 0xFD.
Consider the loop here
for (int i = 0; i < sum; i++)
{
for (int j = 0; j < 20; j++)
{
if (str1[j] == ' ' || str1[j] == '.' || str1[j] == ',' || str1[j] == '?' || str1[j] == ';')
{
i++;
}
else
{
ptr[i][j] = str1[j];
}
}
}
If i is already at (or near) it's maximum value, in the inner loop you might increment it one or more times before reaching ptr[i][j] = str1[j];. At that time i might be way more than sum.
better solution but output is not that as required :
{ char str1[20];
cin.get(str1, 20);
int len, sum = 0;
len = strlen(str1);
int i = 0;
while (str1[i] != '\0')
{
if (str1[i] == ' ' || str1[i] == '.' || str1[i] == ',' || str1[i] == '?' || str1[i] == ';')
{
sum = sum + 1;
}
i++;
}
char **ptr;
ptr = new char*[sum];
for (int i = 0; i < sum; i++)
{
ptr[i] = new char[len];
}
for (int i = 0; i < sum; i++)
{
for (int j = 0; j < len; j++)
{
if (str1[j] == ' ' || str1[j] == '.' || str1[j] == ',' || str1[j] == '?' || str1[j] == ';')
{
ptr[i][j] = str1[j];
i++;
}
else
{
ptr[i][j] = str1[j];
}
}
}
for (int i = 0; i < sum; i++)
{
for (int j = 0; j < len; j++)
{
cout << ptr[i][j];
}
cout << endl;
}
for (int i = 0; i < sum; i++)
{
delete[] ptr[i];
}
delete[] ptr;
system("pause");
return 0;}

c++ encryption with rotation

I'm having some issues in creating a function that encrypts a word using a rotation number the user inputs. Here is what I have so far:
string encryptWord(string word, int num)
{
string newWord;
newWord = word;
for(int i = 0; i < word.length(); i++)
{
newWord[i] = tolower(word[i]);
if((word[i] >= 'a') && (word[i] <= 'z'))
{
newWord[i] = word[i] + (num % 26);
if(newWord[i] > 'z')
newWord[i] = newWord[i] - 26;
}
}
return newWord;
}
now in my main when I test it out with
cout << encryptWord("xyz", 6);
the output I get is: de
Similarly, for decryption I have
string decryptRotWord(string word, int num)
{
string newWord;
num = num % 26;
int index;
for(int i = 0; i < word[i]; i++)
{
newWord[i] = tolower(word[i]);
if(word[i] >= 'a' && word[i] <= 'z')
{
index = word[i] - num;
if(index < 'a')
index = index + 26;
newWord[i] = index;
}
}
return newWord;
}
however, for this one, it does not output anything when I test with
cout << decryptRotWord("vdds", 2);
In your decrypt function, I think you have a mistake on the loop end condition:
for(int i = 0; i < word[i]; i++)
As in the encrypt function, you should iterate over length
for(int i = 0; i < word.length(); i++)
When your for loop arrives to the letter 'z', it does 'z' + 6. But that goes beyond the max length of a char (127). You get an undefined behavior from that.
You should implement a way of starting to count from 'a' whenever you check the encryption goes beyond 'z'.
For the decryption, same as mentioned before, you want to test :
i < word.length()

Converting a do-while loop into a while loop

My code is this I just want to convert my do-while loop into a for loop or a while loop how do I do that. The point of the program is to reverse the input word. like if you put in abc it would output as cba.
int main()
{
while (i < --length - 1);
cout << word << endl;
return 0;
}
The traditional way to convert a while loop into a for loop takes this form:
// While loop
int i = 0;
while( i < n ) {
// Amazing things happen here
i++;
}
// Equivalent for loop
for( int i = 0; i < n; i++ ) {
// Amazing things still happen here
}
Therefore, applied to your code it would look something like:
char ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
for( int i = 0, length = word.length(); i < --length - 1; i++ ) {
char ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
}
Note that since the do-while loop executes the body of the loop before testing, I had to put one copy of the loop body out front. To avoid having to update two different copies of the code, you may want to extract the loop body into a function, which is then called in front of the loop and in the loop body.
And for a while loop version:
int i = 0, length = word.length();
char ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
while( ++i < --length ) {
char ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
}
An alternative is this, which doesn't bother doing anything with strings of size 0 or 1:
int length = word.length();
if (length > 1)
{
int i = 0;
char ch;
while (i < length)
{
ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
i++;
length--;
}
}
For version:
int length = word.length();
if (length > 1)
{
char ch;
for(int i = 0; i < length; i++, length--)
{
ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
}
}