Why aren't the words getting calculated properly in C++? - c++

I was creating the program for my friend who is interested in numerology and wants a way to calculate the value of words faster. But even though there are no errors and/or warnings, but the words' values aren't being calculated correctly. For example, "mark" has a value of 9, but the program shows 2. If you can figure out what the problem is, then pls help me. Thank you so much!
My Code:
#include <iostream>
#include <string>
int value{0};
void clear();
int main(void)
{
int number{0};
std::string response;
bool run = true;
while (run)
{
clear();
value = 0;
number = 1;
response = "";
std::cout << "How many words to evalute?:\n> ";
std::cin >> number;
std::cin.ignore();
clear();
std::string* pPhrase = new std::string[number];
int* pValue = new int[number];
for (int i = 0; i < number; ++i) // could replace "number" with "sizeof(pPhrase)/sizeof(pPhrase[0])"
{
std::cout << "Enter Word #" << i+1 << " (or type your full phrase):\n> ";
std::cin >> pPhrase[i];
for (char j : pPhrase[i])
{
value = 0;
j = std::tolower(j);
if (j == 'a' || j == 'i' || j == 'j'
|| j == 'q' || j == 'y')
value += 1;
if (j == 'b' || j == 'k' || j == 'r')
value += 2;
if (j == 'c' || j == 'g' || j == 'l'
|| j == 's')
value += 3;
if (j == 'd' || j == 'm' || j == 't')
value += 4;
if (j == 'e' || j == 'h' || j == 'n'
|| j == 'x')
value += 5;
if (j == 'u' || j == 'v' || j == 'w')
value += 6;
if (j == 'o' || j == 'z')
value += 7;
if (j == 'f' || j == 'p')
value += 8;
pValue[i] = value;
value = 0;
std::cout << '\n';
clear();
}
}
std::cin.ignore();
std::cin.clear();
std::cout << "\n\n";
for (int i = 0; i < number; ++i)
std::cout << "Value of \"" << pPhrase[i] << "\": " << pValue[i] << '\n';
//std::cin.ignore();
std::cin.clear();
std::cout << "Would you like to evaluate another phrase? (Y/n):\n> ";
std::getline(std::cin, response);
delete[] pPhrase;
delete[] pValue;
if (response[0] == 'y' || response[0] == 'Y'
|| response.empty() || response[0] == ' ')
{
std::cout << "\n\n";
continue;
}
break;
}
std::cout << "Exiting...";
system("killall Terminal");
std::cout << "\n\n\n";
return 0;
}
void clear()
{
system("clear");
}

You could make your program run faster by using a lookup table:
static const int table[26] = {
/* a */ 1, /* b */ 2, /* c */ 3, /* d */ 4, /* e */ 5,
/* f */ 8, /* g */ 3, /* h */ 5, /* i */ 1, /* j */ 1,
/* k */ 2, /* l */ 3, /* m */ 4, /* n */ 5, /* o */ 7,
/* p */ 8, /* q */ 1, /* r */ 2, /* s */ 3, /* t */ 4,
/* u */ 6, /* v */ 6, /* w */ 6, /* x */ 5, /* y */ 1,
/* z */ 7,
};
// ...
if (isalpha(j))
{
const int table_index = j - 'a';
const letter_value = table[table_index];
pValue[i] = letter_value;
//...
}
Print the assembly language for your code fragment, then print the assembly language for the above code fragment. Compare.

Look at all the places where you set value to zero. You do it before main() begins (which is not very useful, actually). Then, bizarrely, you set value to zero at both the start and end of your inner for loop, which means that all the value += statements in that for loop might as well be value = statements. You keep value from accumulating value.
How to solve this? First, get rid of all the value = 0 statements inside your inner for loop. Second, add int value = 0; before the inner for loop, like this:
int value = 0;
for (char j : pPhrase[i])
{
// ...
}
At this point, you might as well get rid of int value{0}; above main(). That step isn't absolutely necessary, but that declaration of value is totally unneeded.
Also, DO NOT put system("killall Terminal"); in your sample code. It's very unfriendly, since it kills the very command line on which you want others to run your sample code.
(In general, using system() at all is a bad idea, since it's unportable.)

There are several issues. The main issue is that on line 70, pValue[i] = value; is incorrectly positioned inside the for loop.
Here is a fixed version:
#include <iostream>
#include <string>
using namespace std;
int value{0};
void clear();
int main() {
int number{0};
string response;
while (true) {
clear();
value = 0;
number = 1;
response = "";
cout << "How many words to evaluate?:\n> ";
cin >> number;
cin.ignore();
clear();
auto *pPhrase = new string[number]{};
int *pValue = new int[number]{};
for (int i = 0; i < number; ++i) // could replace "number" with "sizeof(pPhrase)/sizeof(pPhrase[0])"
{
cout << "Enter Word #" << i + 1 << " (or type your full phrase):\n> ";
cin >> pPhrase[i];
for (char j: pPhrase[i]) {
j = tolower(j);
if (j == 'a' || j == 'i' || j == 'j'
|| j == 'q' || j == 'y')
value += 1;
if (j == 'b' || j == 'k' || j == 'r')
value += 2;
if (j == 'c' || j == 'g' || j == 'l'
|| j == 's')
value += 3;
if (j == 'd' || j == 'm' || j == 't')
value += 4;
if (j == 'e' || j == 'h' || j == 'n'
|| j == 'x')
value += 5;
if (j == 'u' || j == 'v' || j == 'w')
value += 6;
if (j == 'o' || j == 'z')
value += 7;
if (j == 'f' || j == 'p')
value += 8;
cout << '\n';
clear();
}
pValue[i] = value;
value = 0;
}
cin.ignore();
cin.clear();
cout << "\n\n";
for (int i = 0; i < number; ++i)
cout << "Value of \"" << pPhrase[i] << "\": " << pValue[i] << '\n';
cin.clear();
cout << "Would you like to evaluate another phrase? (Y/n):\n> ";
getline(cin, response);
delete[] pPhrase;
delete[] pValue;
if (response[0] == 'y' || response[0] == 'Y'
|| response.empty() || response[0] == ' ') {
cout << "\n\n";
continue;
}
break;
}
cout << "Exiting...";
system("killall Terminal");
cout << "\n\n\n";
return 0;
}
void clear() {
system("clear");
}

Related

Counting occurrence of each character in string C++

So i wanted to count all the characters in a string and categorized them in vowels, consonants, and specials character. For example;
Enter string: sentence example ..
Vowels: e(5) a(1)
Consonants: s(1) n(1) t(1) c(1) x(1) m(1) p(1) l(1)
Specials: blank space .(2)
Here's coding:
void characterType(string input)
{
int vowel = 0;
int consonant = 0;
int special = 0;
int n = input.size();
int freq[26];
memset(freq, 0, sizeof(freq));
for (int i = 0; i < n; i++)
{
freq[input[i] - 'a']++;
}
cout<<"Vowels: ";
for (int i = 0; i < n; i++)
{
char character = input[i];
if(isalpha(character))
{
character = tolower(character);
if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character == 'u')
{
cout<<input[i]<<freq[input[i] - 'a']<<" ";
}
}
}
cout<<endl;
cout<<"Consonants: ";
for (int i = 0; i < n; i++)
{
char character = input[i];
if(isalpha(character))
{
character = tolower(character);
if (character != 'a' || character != 'e' || character != 'i' || character != 'o' || character != 'u')
{
cout<<input[i]<<freq[input[i] - 'a']<<" ";
}
}
}
cout<<endl;
cout<<"Specials: ";
for (int i = 0; i < n; i++)
{
char character = input[i];
if(!isalpha(character))
{
if(character == ' ')
{
cout<<"[black space]"<<freq[input[i] - 'a']<<" ";
}
else
cout<<input[i]<<freq[input[i] - 'a']<<" ";
}
}
}
And heres what ive got so far:
How do i make it not repeat the same character and why does special characters is not counting?
Since you want to do this and it's not some type of assignment, here's how I would approach the problem, using modern C++ features:
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
int main() {
std::map<char, std::size_t> occurrance;
std::string input{"This is A long string with lots of characters in it. AAA$#!#$!^^! "};
auto is_vowel = [] (char c) -> bool
{
auto lc = std::tolower(c);
return
c == 'a' ||
c == 'e' ||
c == 'i' ||
c == 'o' ||
c == 'u';
};
auto is_special = [] (char c) -> bool
{
// use ascii table to find only "non-special characters"
if(c < '0') return true;
if(c > '9' && c < 'A') return true;
if(c > 'Z' && c < 'a') return true;
if(c > 'z') return true;
return false;
};
auto vowels = std::count_if(
input.begin(),
input.end(),
is_vowel);
auto special = std::count_if(
input.begin(),
input.end(),
is_special);
for(auto c : input)
{
occurrance[c] += 1;
}
std::cout << "Vowels: " << vowels << '\n';
std::cout << "Special: " << special << '\n';
for(auto [c, count] : occurrance)
{
std::cout << c << " -> " << count << '\n';
}
return 0;
}
https://ideone.com/YVaDiI
This does the job, although you can make the output prettier... and take the uppercase letters into account.
void printCharWithFreq(string str)
{
int v=0, c=0, s=0;
// size of the string 'str'
int n = str.size();
// 'freq[]' implemented as hash table
int freq[SIZE];
// initialize all elements of freq[] to 0
memset(freq, 0, sizeof(freq));
// accumulate freqeuncy of each character in 'str'
for (int i = 0; i < n; i++)
freq[str[i] - 'a']++;
// traverse 'str' from left to right
for (int i = 0; i < n; i++) {
// if frequency of character str[i] is not
// equal to 0
if (freq[str[i] - 'a'] != 0) {
// print the character along with its
// frequency
if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ||
str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U')
{ cout<<"Vowel: " << str[i] << freq[str[i] - 'a'] << " "<<endl; v+=freq[str[i] - 'a']; }
else if(str[i] == ' ' || str[i] == '.')
{ cout<<"Specials"<<endl; s++; }
else
{ cout<<"Consonant: " << str[i] << freq[str[i] - 'a'] << " "<<endl; c+=freq[str[i] - 'a']; }
// update frequency of str[i] to 0 so
// that the same character is not printed
// again
freq[str[i] - 'a'] = 0;
}
}
cout<<"Number of vowels: "<<v<<endl;
cout<<"Number of consonants: "<<c<<endl;
cout<<"Number of specials "<<s<<endl;
}
Then test it in the main function like
int main() {
string str = "some text . .";
printCharWithFreq(str);
return 0;
}
Basically, frequency is updated so it doesn't print the same character again, as it says in the comments. You also made a mistake in your code where you wrote:
character != 'a' || character != 'e' || character != 'i' || character != 'o' || character != 'u'
It is a consonant only if the input is different than ALL of the vowels, meaning you have to put &&, not ||.
As for the special characters, they can be counted with a simple counter.
The rest, I think, is clear from the comments in the code.
I adapted the code from the following source:
https://www.geeksforgeeks.org/print-characters-frequencies-order-occurrence/

How would I set up a grid system that shows what each row/column is?

I've been stuck for hours trying to make a grid similar to the one in battleship, with letters on one side and numbers on the other, but I cant get it to work, with it either cycling through all letters when I'd like for it just to stick with a certain set (I.E the first time it goes from a to j, but the next time it goes k to t), and the numbers keep on looping when I just want 1 to 10.
Thank you!
#include <iostream>
#include <string>
bool gameend = true;
char cUserInput;
class boat
{
int length;
int x1, x2, y1, y2;
int health;
};
int iXPlayerPos = 2;
int iYPlayerPos = 2;
int iXShipPos = 2;
int iYShipPos = 2;
int iXCoffeePotPos = 3;
int iYCoffeePotPos = 7;
// Room Bounds (square room in positive quadrant)
int iKitchenWallMax = 10; // max length of our walls, reused from older grid code
char cSpace = ' ';
char cPlayer = 'p';
char cShip = 'O';
int cHorizontalWall = 1;
char cVerticalWall = 'a';
int a[10][10];
int main()
{
std::cout << "Where do you want the ship to go?";
std::cin >> iXShipPos >> iYShipPos;
movement:
for (int iTop = 0; iTop <= iKitchenWallMax + 10; iTop++)
{
std::cout << cHorizontalWall, cHorizontalWall++;
if (cHorizontalWall > 10 ) {
cHorizontalWall = 0;
// trying to only show numbers 1 to 10, for the 10 rows
}
}
std::cout << std::endl;
for (int cols = 0; cols < iKitchenWallMax; cols++)
{
std::cout << cVerticalWall; // put letters a to j here
for (int rows = 0; rows < iKitchenWallMax; rows++)
{
std::cout << " " << a[rows][cols];
if (cols == iYPlayerPos && rows == iXPlayerPos)
{
std::cout << cPlayer;
}
else if (cols == iXShipPos && rows == iYShipPos)
{
std::cout << cShip;
}
}
std::cout << std::endl;;
}
for (int iBottom = 0; iBottom <= iKitchenWallMax + 10; iBottom++)
{
std::cout << cHorizontalWall;
}
std::cout << std::endl;
// USER INPUT
char cInput = 'z';
for (; cInput != 'y' && cInput != 'n' && cInput != 'w' && cInput != 'a' && cInput != 's' && cInput != 'd'; (std::cin >> cInput))
{
std::cout << "Please enter 'y' or 'n' and hit return to proceed" << std::endl;
}
cUserInput = cInput;
return 0;
}

Computer Player for a Gomoku Game in C++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
A few time ago I made a game similar to Gomoku in C++ that is taking between two players.
Now I want to make it Player vs Computer.
I tried to do it in simplest way, by making a function of computer to pick a random cell but I still haven't succeeded.
I understood that in order of getting a random number I can use rand() and for a letter something like this:
char letters[] = "abcdefghijklmnopqrstuvwxyz";
char x = letters[rand() % 26];
Can someone help me and describe how to implement a computer player?
This is my implementation so far:
#include <iostream>
#include <iomanip>
using namespace std;
void print_table(int x[][15]) {
system("cls");
for (int i = 0; i < 15; i++) {//the loop that use to print out the english character row
if (i == 0)
cout << setw(4) << "A";
else if (i == 1)
cout << " B";
else if (i == 2)
cout << " C";
else if (i == 3)
cout << " D";
else if (i == 4)
cout << " E";
else if (i == 5)
cout << " F";
else if (i == 6)
cout << " G";
else if (i == 7)
cout << " H";
else if (i == 8)
cout << " I";
else if (i == 9)
cout << " J";
else if (i == 10)
cout << " K";
else if (i == 11)
cout << " L";
else if (i == 12)
cout << " M";
else if (i == 13)
cout << " N";
else if (i == 14)
cout << " O";
else if (i == 15)
cout << " P";
}
cout << endl;
for (int i = 0; i < 15; i++) {
cout << setw(2) << i;//print out the row number
for (int j = 0; j < 15; j++) {//print out the board game.
if (x[i][j] == 0) {//the inital value is 0, so when the block is 0 then print out the '.'
cout << " .";
}
else if (x[i][j] == 1) {//when the player O input the block then the value will adding one then if check the block is one then output the 'o'
cout << " O";
}
else if (x[i][j] == 2) {//when the player X input the block then the value will adding two then if check the block is two then output the 'x'
cout << " X";
}
}
cout << endl;
}
}
int check_player(int p) {
if (p == 1) {//change the player everytime before the next loop compile
p++;
}
else {
p--;
}
return p;
}
void input_value(int &t, int &n, int p, int x[][15]) {
char eng;
int number;
do {//the loop that ask for the user input the location.
cout << "player ";
if (p == 1) {
cout << "O";
}
else {
cout << "X";
}
cout << ", make a move: ";
cin >> eng;//input the location
cin >> number;
if (eng == 'A')//change the character to different number
t = 0;
else if (eng == 'B')
t = 1;
else if (eng == 'C')
t = 2;
else if (eng == 'D')
t = 3;
else if (eng == 'E')
t = 4;
else if (eng == 'F')
t = 5;
else if (eng == 'G')
t = 6;
else if (eng == 'H')
t = 7;
else if (eng == 'I')
t = 8;
else if (eng == 'J')
t = 9;
else if (eng == 'K')
t = 10;
else if (eng == 'L')
t = 11;
else if (eng == 'M')
t = 12;
else if (eng == 'N')
t = 13;
else if (eng == 'O')
t = 14;
if (!(eng >= 'A'&&eng <= 'M') || !(number >= 0 && number <= 14) || x[number][t] != 0) {//when the input wrong, output the statement to ask anouther input and loop again.
cout << "Invaid input, Try again!" << endl;
continue;
}
else {//if no problem then this input loop is break and jump to the next statement
break;
}
} while (1);//Because it will break as well so the do-while loop is no any requirement
n = number;
}
int main() {
const int num = 15;//the number for constant the array row and column value
char check_e;//for the user input the column
int R[num][num] = { 0 }, check_n, player = 1, buger = 0, transfer, playerO_win = 0, playerX_win = 0, draw = 0, check_draw;//the variable that for user input or checking the game statment
do {//launch the loop for the user input again and again
check_draw = 0;//reset the checking of draw
print_table(R);
input_value(transfer, check_n, player, R);
R[check_n][transfer] += player;//change the value according the player's input and the player name.
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
if (i <= 8 && R[j][i] != 0 && (R[j][i] == R[j][i + 1] && R[j][i] == R[j][i + +2] && R[j][i] == R[j][i + 3] && R[j][i] == R[j][i + 4])) {//the checking for the row bingo
if (R[j][i] == 1) {
playerO_win++;
break;
}
else {
playerX_win++;
break;
}
}
else if (j <= 8 && R[j][i] != 0 && (R[j][i] == R[j + 1][i] && R[j][i] == R[j + 2][i] && R[j][i] == R[j + 3][i] && R[j][i] == R[j + 4][i])) {//the checking for the column bingo
if (R[j][i] == 1) {
playerO_win++;
break;
}
else {
playerX_win++;
break;
}
}
else if (j <= 8 && i <= 8 && R[j][i] != 0 && (R[j][i] == R[j + 1][i + 1] && R[j][i] == R[j + 2][i + 2] && R[j][i] == R[j + 3][i + 3] && R[j][i] == R[j + 4][i + 4])) {//the checking for the \ situation.
if (R[j][i] == 1) {
playerO_win++;
break;
}
else {
playerX_win++;
break;
}
}
else if ((j >= 4 || i >= 4 || i <= 8) && R[j][i] != 0 && (R[j][i] == R[j - 1][i + 1] && R[j][i] == R[j - 2][i + 2] && R[j][i] == R[j - 3][i + 3] && R[j][i] == R[j - 4][i + 4])) {//the checking for the / situation
if (R[j][i] == 1) {
playerO_win++;
break;
}
else {
playerX_win++;
break;
}
}
for (int i = 0; i < num; i++) {//the loop for checking the draw
for (int j = 0; j < num; j++) {//this loop will check for every time compilation.
if (R[j][i] == 0)//when there are any empty block then the check_draw will adding, the draw situation is the check_draw be 0
check_draw++;
}
}
if (check_draw == 0) {//when the check_draw equal to 0 which mean the situation is no empty block
draw++;
break;
}
}
if (playerO_win != 0 || playerX_win != 0 || draw == 1)//break the second loop
break;
}
if (playerO_win == 1 && playerX_win == 0) {// when the player win print the block game again and print out the win statement
print_table(R);
cout << "player O wins!" << endl;
break;
}
else if (playerX_win == 1 && playerO_win == 0) {//the other player win the game
print_table(R);
cout << "player X wins!" << endl;
break;
}
else if (draw == 1) {//the draw block game print
print_table(R);
cout << "Draw game!" << endl;
break;
}
player = check_player(player);
} while (1);//in fact it is no need for the loop statement, because most of the situation will have a break statement for out of the loop
return 0;
}
Here's how I would implement it probably based on your initial implementation:
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
#define SIZE 10
#define LINE_LENGTH 4
#define COMPUTER_O_PLAYER true
#define COMPUTER_X_PLAYER false
void print_board(unsigned char x[SIZE][SIZE]) {
cout << " ";
for (int i = 0; i < SIZE; i++) { // The loop that use to print out the english character row.
cout << (char) ('A' + i) << " ";
}
cout << endl;
for (int i = 0; i < SIZE; i++) {
cout << setw(2) << i; // Print out the row number.
for (int j = 0; j < SIZE; j++) {//print out the board game.
if (x[i][j] == 0) { // Unoccupied tile.
cout << " .";
} else if (x[i][j] == 1) { // The tile belongs to X.
cout << " X";
} else { // The tile belongs to O.
cout << " O";
}
}
cout << endl;
}
}
void get_position(int &x, int &y, bool player, unsigned char board[SIZE][SIZE]) {
char eng;
// The loop that ask for the user input the location.
do {
cout << "Player " << (player ? "X" : "O") << ", make a move: ";
cin >> eng;
y = toupper(eng) - 'A';
cin >> x;
if (!(x >= 0 && x < SIZE) || !(y >= 0 && y < SIZE) || board[x][y] != 0) {
// When the input wrong, output the statement to ask another input and loop again.
cout << "Invalid input, Try again!" << endl;
continue;
} else { // If no problem then this input loop is break and jump to the next statement.
break;
}
} while (true);
}
void get_random_position(int &x, int &y, bool player, unsigned char board[SIZE][SIZE]) {
do {
x = rand() % SIZE;
y = rand() % SIZE;
} while ((!(x >= 0 && x < SIZE) || !(y >= 0 && y < SIZE) || board[x][y] != 0));
cout << "Player " << (player ? "X" : "O") << " chose: " << (char) ('A' + y) << x << endl;
}
unsigned int
count_in_direction(unsigned char board[SIZE][SIZE], unsigned int x, unsigned int y, short int m_x, short int m_y) {
unsigned int count = 0;
unsigned char tile = board[x][y];
while (((x + m_x >= 0) && (x + m_x < SIZE)) && ((y + m_y >= 0) && (y + m_y < SIZE)) &&
(board[x + m_x][y + m_y] == tile)) {
x += m_x;
y += m_y;
count++;
}
return count;
}
bool full_line(unsigned char board[SIZE][SIZE], unsigned int x, unsigned int y) {
const short int directions[4][2] = {{1, 0},
{1, -1},
{0, 1},
{1, 1}};
for (const auto &direction : directions) {
if (LINE_LENGTH - 1 <= (count_in_direction(board, x, y, direction[0], direction[1]) +
count_in_direction(board, x, y, -direction[0], -direction[1])))
return true;
}
return false;
}
int main() {
// The variable that for user input or checking the game state.
unsigned char board[SIZE][SIZE] = {0};
int x, y;
bool player = true;
bool draw;
srand(time(nullptr));
// Run the game.
do {
print_board(board);
if ((player && COMPUTER_X_PLAYER) || (!player && COMPUTER_O_PLAYER)) {
get_random_position(x, y, player, board);
} else {
get_position(x, y, player, board);
}
board[x][y] = player ? 1 : 2;
if (full_line(board, x, y)) {
print_board(board);
cout << "player " << (player ? "X" : "O") << " wins!" << endl;
break;
}
draw = true;
for (int k = 0; (k < SIZE) && draw; k++) {
for (int l = 0; (l < SIZE) && draw; l++) {
if (board[k][l] == 0) draw = false;
}
}
if (draw) {
print_board(board);
cout << "Draw game!" << endl;
break;
}
player = !player;
} while (true);
return 0;
}
Please take a deep look in this implementation and internalize its approach, it also support both players as user, user and computer, and both computer.
Some insights:
Don't use long if ... else when there are simpler ways.
Use the correct data types for variables.
Use indicative variables naming.
Use loops where possible, again, not long if ... else.
Keep the code well formatted.
Use #define to define global constants to use, for easier changes later and readability.
You can indeed use rand, but you don't need to get a character, you can get an index straight away and avoid the conversion.

c++ Expression: string subscript out of range error

hello i am new to programming but every time i run this code i get the error "c++ Expression: string subscript out of range" i am pretty sure that the error is in the second for loop
#include<iostream>
#include<string>
#include <algorithm>
using namespace std;
int main()
{
string x;
string n;
cin >> x;
for (int i = 0; i <= x.length(); i++){
if (x[i] == 'a' || x[i] == 'e' || x[i] == 'i' || x[i] == 'o' || x[i] == 'u' || x[i] == 'y')
{
x[i] = ' ';
}
}
x.erase(remove_if(x.begin(), x.end(), isspace), x.end());
int f = x.length() * 2;
for (int i = 0; i <f-1; i+=2){
n[i] = '.';
}
cout << n << endl;
}
for (int i = 0; i <= x.length(); i++)
should be:
for (int i = 0; i < x.length(); i++)
because index starts from 0
x[x.length()] out of range
can not use n[index] when the size of n is 0,use n.push_back()
for (int i = 0; i < x.length(); i++){ //error
if (x[i] == 'a' || x[i] == 'e' || x[i] == 'i' || x[i] == 'o' || x[i] == 'u' || x[i] == 'y')
{
x[i] = ' ';
}
}
x.erase(remove_if(x.begin(), x.end(), isspace), x.end());
int f = x.length() * 2;
for (int i = 0; i <f-1; i+=2){
n[i] = '.'; // n.push_back('.');
}
cout << n <
< endl;
If you are trying to remove all the vowels from your input string, you do not need to run two separate loops. You are already using std::remove_if, just add lambda shown in following code and you will have your desired output.
#include <iostream>
#include <algorithm>
#include <string>
#include <cctype>
using namespace std;
int main() {
std::string str = "This is test of vowels aeiou to be removed. Also the upper case AEIOU.";
std::cout << "Original String: " << str << std::endl;
str.erase(std::remove_if(str.begin(), str.end(), [](char x) {
return (x == 'a'|| x == 'e' || x == 'i' || x == 'o' || x == 'u' || x == 'y'
|| x == 'A'|| x == 'E' || x == 'I' || x == 'O' || x == 'U' || x == 'Y')
}), str.end());
std::cout << "String with vowels removed: " << str << std::endl;
// Not sure what you are trying to achieve with this code.
int f = x.length() * 2;
for (int i = 0; i <f-1; i+=2)
{
n[i] = '.';
}
return 0;
}
Here is the LiveDemo
You have 3 bits of code causing errors:
1) Your first error occurs because you should be checking that i < x.length() in the first loop condition, not that i <= x.length() . Even better, calculate the length once and then use that value in the loop condition to avoid calling x.length() repeatedly. Your first loop should look like this:
int length = x.length();
for (int i = 0; i < x.length(); ++i)
note: ++i is quicker than i++ and in this case using ++i would not make a difference to the logic.
2) Your second error is due to the line int f = x.length() * 2 because you are doubling the length of the array and then using that number to iterate through the array. For example, if your array has a length() of 5 then int f = x.length() * 2 would mean that f = 10 but if the length of the array is 5 than accessing the array with any number greater than 4 (array index starts at zero) would produce an error. In your second loop condition you do this
for (int i = 0; i < f-1; i+=2 ) {
n[i] = '.' // i could easily be more than 4 at this point
}
To fix you second problem, take out the * 2 from int f = x.length() * 2
3) Your third is because you haven't given the n string object a value yet you are accessing it using array indexing []

Counting Multi-Character Characters in String

For example, how do you count the occurrence of "TJ" in OAEKOTJEOTJ?
if (s[i] == 'TJ') and (s[i] == 'T'+'J')
x += 1;
First one gives me an error, second one doesn't count. I need a beginner solution to this, I haven't learned very much about c++ commands yet. Thanks
int x = 0
string s;
cin >> s;
for (int i = 0; i < 100; i++)
if (s[i] == T || s[i] == t) && (s[i+1] == J || s[i+1] == j)
x += 1
cout << x << endl;
That's the excerpt from my code, it doesn't count any tj, tJ, Tj or TJ
Try using:
if(s[i] == 'T' && s[i+1] == 'J') // and make sure you do not run out of bounds of string with index i.
x += 1;
EDIT:
Based on your code:
int x = 0
string s;
cin >> s;
for (int i = 0; i < 100; i++)
if (s[i] == T || s[i] == t) && (s[i+1] == J || s[i+1] == j)
x += 1
cout << x << endl;
You should do it like following:
int x = 0
string s;
cin >> s;
for (int i = 0; i < s.length()-1; i++) // use size of string s.length()-1 to iterate the string instead of 100
if (s[i] == 'T' || s[i] == 't') && (s[i+1] == 'J' || s[i+1] == 'j') // compare the ascii values of characters like - 'T' 'J' etc.
x += 1
cout << x << endl;
std::string provides a function find which searches the string for substrings, including multi-character substrings (below, I am using C++11 syntax):
#include <iostream>
#include <string>
int main()
{
using namespace std;
string text { "OAEKOTJEOTJ" };
unsigned int occ { 0 };
size_t pos { 0 };
for (;;) {
pos = text.find("TJ",pos); // Search for the substring, start at pos
if (pos == string::npos) // Quit if nothing found
break;
++pos; // Continue from next position
++occ; // Count the occurrence
}
std::cout << "Found " << occ << " occurrences." << std::endl;
}
The way it's done above we advance by one character only after each match. Depending on whether/how we want to deal with overlapping matches, we might want to advance pos by the length of the search pattern. (See chris's comment as well.)
Try this:
#include <locale> // for tolower() function
string tolower(string s) {
tolower(s[0]);
tolower(s[1]);
return s;
}
...
int main() {
string s;
cin >> s;
int n = s.size(),cont = 0;
for(int i = 0; i < n ; ++i) {
if(tolower(s.substr(i,2)) == "tj") {
++cont;
}
}
cout << cont << endl;
return 0;
}