I am reading C++ right now ,and got stuck in the following program.
When I provide string with lower case letter, it provides a fine output, but when I go for upper case letters, it gets stuck after the input.
Here is the code:
`#include <iostream>`
#include <stdio.h>
#include "string.h"
using namespace std;
class base {
public:
int array(){
int i, n, p, z = 0;
char g[50];
string c[50];
char abc;
cout << "Enter the name :" << endl;
cin >> g;
i = 0;
while (g[i] != 0)
if ((g[i] >= 'a' && g[i] <= 'z') || (g[i] <= 'A' && g[i] >= 'Z')){
z++;
i++;
}
cout << "name is of " << z << " elements" << endl;
{
for (p = 0; p < z; p++)
cout << "a[" << p + 1 << "]=" << g[p] << endl;
}
cout << "enter the element no.:";
cin >> n;
if(n >0 && n <= z){
cout << "a[" << n << "]=" << g[n-1] << endl;
}
for (p = 0; p < z; p++){
char integer_string[50];
int integer = p+1;
sprintf(integer_string, "%d", integer);
char other_string[50] = "g[";
strcat(other_string, integer_string);
strcat(other_string, "]");
c[p]= other_string;
}
cout << "Enter the character :";
cin >> abc;
for (p = 0; p < z; p++){
if(g[p] == abc){
cout <<abc<< "=a[" << p + 1 << "]"<< endl;
break;
}
}
return 0;
}
};
//--------------------------------------------------------------
int main(){
base b;
b.array();
return 0;
}
Could you tell me what is the problem in my program?
Try changing
if ((g[i] >= 'a' && g[i] <= 'z') || (g[i] <= 'A' && g[i] >= 'Z'))
to
if ((g[i] >= 'a' && g[i] <= 'z') || (g[i] >= 'A' && g[i] <= 'Z'))
and deleting the three ` , two in the first line and one in the last line.
UPDATE
Adding #incude <cctype> to the head of the code and using
if (islower(g[i]) || isupper(g[i]))
is better. To avoid depending to the character code.
if (isalpha(g[i])) may also work.
Related
I am trying to make this shape from the code below. I'm confused as to how to make it print the 2nd row, second to last star without it skipping and printing the extra space before printing the star. Once that is figured out would the bottom half, when the stars expands back out, would the code be similar to the top half? I have tried a couple combinations of code between c and r but I have been stuck with what I currently.
---------------------- //row 0
* *| //row 1
* * * *| //row 2
* * * * * *|
* * * * * * * *|
* * * * * * * * * *|
* * * * * * * * * * *|
* * * * * * * * * *|
* * * * * * * *|
* * * * * *|
* * * *|
* *|
----------------------
#include <iostream>
using std::cout; using std::cin; using std::endl;
int main() {
cout << "Enter a positive odd number less than 40: ";
int num = 0;
int z = 1;
for (int a = 0; a < 3; ++a)
{
cin >> num;
if (num < 38 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl << endl;
for (int r = 0; r < num; ++r) //outer loop/rows
{
for (int c = 0; c < num; ++c) //inner loop/columns
{
if (r == 0) cout << "--"; //top of square
else if (c >= r + r - c && c < num - 1)
cout << " ";
//else if (c == num - 1) cout << "*|";
else if (r == num - 1) cout << "--"; //bottom of square
else if (c == num - 1) cout << "*|"; //right side of square
else if (r > c) cout << "* ";
}
cout << endl;
}
break;
}
else cout << "Please enter a positve odd number that is less than 40!" << endl;
}
cout << endl;
}
I just took two variables left=0 & right=num-1 and increased left & decreased right till r<=num/2, after that i reversed the process,when the col <= left or col >=right I printed *.
I hope it will be easy to understand.
Here is the code:
#include <iostream>
using std::cout; using std::cin; using std::endl;
int main() {
cout << "Enter a positive odd number less than 40: ";
int num = 0;
int z = 1;
for (int a = 0; a < 3; ++a)
{
cin >> num;
if (num < 38 && num > 0 && num % 2 == 1)
{
cout << "Thank you!" << endl << endl;
int left=0,right=num-1;
//for printing top line
for(int i = 0; i < num; i++) cout<<"- ";
cout<<"-"<<endl;
for (int r = 0; r < num; ++r) //outer loop/rows
{
//printing columns
for(int c = 0; c < num; c++)
{
if(c <= left || c >= right)
cout<<"* ";
else
cout<<" ";
}
if(r >= num/2) //checking for half of the rows
{
left--;right++;
}
else
{
left++;right--;
}
cout<<"|"<<endl;
}
//for printing last additional line
for(int i = 0; i < num; i++) cout<<"- ";
cout<<"-"<<endl;
break;
}
else cout << "Please enter a positve odd number that is less than 40!" << endl;
}
cout << endl;
}
This approach does it the math way.
Furthermore it draws a full frame with plus-chars at the edges.
Give it a try.
#include <iostream>
#include <cmath>
using std::cout; using std::cin; using std::endl;
int main() {
cout << "Enter a positive odd number less than 40: ";
int num = 0;
int z = 1;
for (int a = 0; a < 3; ++a) {
cin >> num;
if (num < 40 && num > 0 && num % 2 == 1) {
cout << "Thank you!" << endl << endl;
int center = ceil(num / 2.0);
for (int r = 0; r <= num+1; ++r) { //outer loop/rows
for (int c = 0; c <= num+1; ++c) { //inner loop/columns
if (r == 0 || r == num+1) {
if (c == 0 || c == num+1)
cout << "+"; // corner
else
//top or botton of square between corners
if (c == center)
cout << "-";
else
cout << "--";
}
else if (c == 0 || c == num+1) {
cout << "|"; // left or right frame
} else {
// inner part
if ((center-std::abs(center-r)) >= center-std::abs(center-c))
if (c < center)
cout << "* ";
else if (c > center)
cout << " *";
else
cout << "*";
else
if (c == center)
cout << " ";
else
cout << " ";
}
}
cout << endl;
}
} else
cout << "Please enter a positve odd number that is less than 40!" << endl;
}
cout << endl;
}
Just another way (with some more user input checking):
#include <iostream>
#include <string>
#include <limits>
#include <sstream>
using std::cout;
using std::cin;
using std::string;
const auto ssmax = std::numeric_limits<std::streamsize>::max();
const int max_dim = 40;
const int max_iter = 3;
int main() {
cout << "Enter a positive odd number less than " << max_dim << ": ";
int num = 0, counter = 0;
while ( counter < max_iter ) {
cin >> num;
if ( cin.eof() )
break;
if ( cin.fail() ) {
cout << "Please, enter a number!\n";
cin.clear();
cin.ignore(ssmax,'\n');
}
if ( num < max_dim && num > 0 && num % 2 ) {
cout << "Thank you!\n\n";
//top line
string line(num * 2, '-');
cout << line << '\n';
for ( int r = 0, border = num - 1; r < num; ++r ) {
cout << '*';
for ( int c = 1; c < num; ++c ) {
if ( (c > r && c < border) || (c < r && c > border) )
cout << " ";
else
cout << " *";
}
// right border
cout << "|" << '\n';
--border;
}
//bottom line
cout << line << '\n';
++counter;
} else {
cout << "Please, enter a positive odd number that is less than 40!\n";
}
}
cout << std::endl;
}
Or my favorite:
// top line
string line = string(num * 2, '-') + '\n';
cout << line;
// inside lines
int r = 0, border = ( num - 1 ) * 2;
string inside = string(border + 1, ' ') + "|\n";
// top
while ( r < border ) {
inside[r] = '*';
inside[border] = '*';
r += 2;
border -= 2;
cout << inside;
}
// center line
inside[r] = '*';
cout << inside;
// bottom
while ( border > 0 ) {
inside[r] = ' ';
inside[border] = ' ';
r += 2;
border -= 2;
cout << inside;
}
//bottom line
cout << line;
I would like to to print a triangle with a given letter. For example, if I input D, the program should return:
A
AB
ABC
ABCD
So far, I have managed to print all letters until the given one in my example, but as you see this method is not quite effective since I need to do this for all 26 cases since the English alphabet is 26 chars. Is there some way to optimize my code?
#include <iostream>
using namespace std;
int main() {
char i;
cout << "Enter char ";
cin >> i;
int c = static_cast<int>(i);
if (65 < c) {
cout << "A";
cout << endl;
}
if (66 < c) {
cout << "AB";
cout << endl;
}
if (67 < c) {
cout << "ABC";
cout << endl;
}
for (int i = 64; i < c; i++) {
cout << static_cast<char>(i + 1);
}
return 0;
}
You definitely need to work on your comprehension of loops. This one works just fine and it even has some checks on what is typed in and it eventually converts lower case letters into upper casse.
char first = 'A';
char last = 0;
cout << "Enter a char: ";
cin >> last;
fflush(stdin);
cout << "\n\n";
if ((last > 96) && (last < 123)) //97 to 122 are lower case letters
{
last -= 32; //32 is the delta between each lower case letter and its upper case "twin"
}
if ((last > 64) && (last < 91))
{
for (char i = 65; i <= last; i++)
{
for (char j = 65; j <= i; j++)
{
cout << j;
}
cout << "\n";
}
}
else
{
cout << "\nWrong character!!\n\n";
return 0;
}
Use a nested loop structure. Use the outer loop to 'walk' down your triangle,
lineLength = 1;
while(lineLength <= (c - 64)){
...stuff...
lineLength++;
cout << endl;
}
Use the inner loop to 'walk' down the alphabet (you've already done most of this):
for (int i = 0; i < lineLength; i++) {
cout << static_cast<char>(i + 65);
}
Putting it together:
lineLength = 1;
while(lineLength <= (c - 64)){
for (int i = 0; i < lineLength; i++) {
cout << static_cast<char>(i + 65);
}
lineLength++;
cout << endl;
}
I see that someone else has posted a similar answer. Between these two answers, you should be able to find your way. I haven't compiled and run this code, but I believe that it should work or be very close.
Don't harcode ascii integer values into code. Explicitly use the character or string literals (e.g. 'A' instead of 65)
Start with a helper function to print exactly one line
// prints all the characters of the alphabetic sequence from "A" to the final char designated by <c>
void printTriangleLine(char c)
{
if ((c < 'A') || (c > 'Z'))
{
return;
}
for (char x = 'A'; x <= c; x++)
{
cout << x;
}
cout << endl;
}
Then put it all together in your main:
int main()
{
char i;
cout << "Enter char ";
cin >> i;
if ((i < 'A') || (i > 'Z'))
{
return 0;
}
for (char x = 'A'; x <= i; x++)
{
printTriangleLine(x);
}
return 0;
}
We must run the loop from position is above 'A' character
until we reached the charanter you enter
// procead until reached input letter
while (chNew != c)
{
// go to next letter
chNew++;
// start with 'A' until current char + 1
for (int j = 'A'; j < chNew + 1; j++)
cout << (char)j;
// go to next line
cout << endl;
}
in each loop we increment character value by 1 to go to the next value
// go to next letter
chNew++;
inner loop simply print the character from A to next value relative to current chNew + 1, it is because we also want to include current character to our printed line.
Here is your working code.
#include <iostream>
using namespace std;
int main()
{
char i;
cout << "Enter char ";
cin >> i;
int c = static_cast<int>(i);
// start with 'A' - 1 character
char chNew = 'A' - 1;
// procead until reached input letter
while (chNew != c)
{
// go to next letter
chNew++;
// start with 'A' until current char + 1
for (int j = 'A'; j < chNew + 1; j++)
cout << (char)j;
// go to next line
cout << endl;
}
// we have done
return 0;
}
here is my code, im getting error no match for 'operator<=' in 'i <= slovo'
its a program which converts word in each row from capitals to lowercase...
can u help with this?? thanks
#include <iostream>
using namespace std;
int main ()
{
const int max = 100;
string slovo;
int pocet_r;
cout << "Zadaj pocet uloh:" << endl;
cin >> pocet_r;
if(pocet_r >= 1 && pocet_r <=100)
{
// funkcia na zabezpecenie minimalneho poctu chars
for (int i = 0; i <pocet_r; i++)
{
cout << "Uloha " << i+1 << ":" << endl;
cin >> slovo;
if(slovo.size() > max)
{
cout << "slovo musi mat minimalne 1 a maximalne 100 znakov" << endl;
}
while( slovo.size() > max)
{
cin >> slovo;
}
}
for (int i=0; i <= slovo; i++)
{
while (slovo[i] >= 'A' && slovo[i] <= 'Z')
{
slovo[i] = tolower(slovo[i]);
}
}
}else{
cout << "Minimalne 1 a maximalne 100 uloh" << endl;
}
system("pause");
}
i <= slovo tries to compare an integer to a string. With our mighty human brains, we know that 42 is acually larger than "This string", but the compiler isn't as smart, so it just doesn't let you compare integers to strings.
Did you mean to compare i to the string's length (i.e. .length() or .size())?
for (int i=0; i <= slovo.size(); i++)
// |
// You probably want < here though, not <=
slovo is a string, so i <= slovo doesn't make sense.
Did you mean to say i <= slovo.length()?
I think you have to use i <= slove.size() instead of i <= slove().
I'm reading in a sodoku board from a text file. The board is represented by 9 rows of 9 digit numbers, like this:
594632817
123478569
678159234
215346798
346897125
789215346
437561982
851924673
962783451
EDIT
Here are the results when I change the while condition to (input >> char):
Output as chars are read in:
96212486
71931369
48728254
35185947
67350
Output of printArray:
962124867
193136948
728254351
859476735
�$%w��
����QȿȔ
L�`g�Pw
���w�
And here's the output for while (!input.eof()):
�94632817
123478569
678159234
215346798
346897125
789215346
437561982
851924673
962783451
END EDIT
The trouble is, when I place each digit into a multidimensional array, the element at [0][0] appears as a shaded question mark (compiled with g++). The problem only surfaces when I'm printing out the contents of the array, the data as it's read in appears to be fine. For what it's work, this also happens if I cout << board[0][0] from the main function.
Any help would be appreciated!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int createArray(string filename);
bool checkRows(char board[][9]);
bool checkColumns(char board[][9]);
bool checkBoxes(char board[][9]);
void printArray(char board[][9]);
int main ()
{
char board [9][9];
int i = 0;
int j = 0;
int count = 0;
ifstream input("board.txt");
char ch;
while (input >> ch)
{
// ch = input.get();
if (ch != '\n')
{
cout << ch;
board[i][j] = ch;
j++;
if (j % 9 == 0)
{
i++;
}
}
if (j > 8)
j = 0;
if (i > 8)
i = 0;
count++;
if (count % 10 == 0)
cout << endl;
}
input.close();
printArray(board);
cout << checkRows(board) << endl;
cout << checkColumns(board) << endl;
return 0;
}
void printArray(char board[][9])
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
cout << board[i][j];
}
cout << endl;
}
cout << board[0][0] << endl;
cout << board[0][1] << endl;
}
By doing this, reading ch two times.
Remove ch = input.get(); and you will read each number correctly.
while (input >> ch)
{
ch = input.get();
...
}
Again, consider changing condition below to make sure correct endl placement
if (count % 10 == 0)
cout << endl;
to
if (count % 9 == 0)
cout << endl;
i cant seem to figure out what wrong
for some reason it wont compile and it think theres a problem on my jumbleString function
#include <iostream>
#include <iomanip>
#include <string>
#include <istream>
using namespace std;
int main ()
{
int lengthofstring, x, countWords(string str), countConsonant(string str, int), consonant, jumbleString(string str);
string str, str2, wordone;
char options;
cout << "Please enter a word, a sentence, or a string of numbers." << endl;
getline(cin, str);
//cin >> str;
lengthofstring = str.length();
str2=str;
bool another= true;
while (another)
{
cout << '\n' << "USE THIS MENU TO MANIPULATE YOUR STRING" << endl;
cout << "---------------------------------------" << endl;
cout << "1) Inverse String" << endl;
cout << "2) Reverse String" << endl;
cout << "3) To Uppercase" << endl;
cout << "4) Jumble String" << endl;
cout << "5) Count Number Words" << endl;
cout << "6) Count Consonants" << endl;
cout << "7) Enter a Different String" << endl;
cout << "8) Print the String" << endl;
cout << "Q) Quit" << endl;
cin >> options;
switch (options)
{
case '1':
for (x = 0; x < lengthofstring; x++)
{
if (islower(str[x]))
str[x] = toupper(str[x]);
else if (isupper(str[x]))
str[x] = tolower(str[x]);
}
cout<< str;
break;
case '2':
for (x = 0; x < lengthofstring; x++)
{
str2[x] = str[lengthofstring-1-x];
}
cout<< str2;
break;
case '3':
{
for (x = 0; x < lengthofstring; x++)
{
if (islower(str[x]))
str[x] = toupper(str[x]);
}
cout<< str;
}
break;
case '4':
jumbleString(str);
break;
case '5':
cout << countWords(str);
break;
case '6':
consonant = 0;
cout<< countConsonant(str, consonant);
break;
case '7':
cout << "Please enter another word, a sentence, or a string of numbers." << endl;
cin.ignore();
getline(cin, str);
cout << str <<endl;
break;
case '8':
cout<< str2;
break;
case 'q':
another = false;
break;
}
}
cin.get();
cin.get();
return 0;
}
void jumbleString(string str)
{
int length = str.length();
int j, k;
for(int i = 0; i < length; j++)
{
k = rand() % length;
j = rand() % length;
char c = str[j];
str[j] = str[k];
str[k] = c;
}
cout << str<<endl;
}
int countWords(string str)
{
int length = str.length();
int words = 1;
for(int size = 1; length > size; size++)
{
if (str[size] == ' ' && str[size-1] != ' ')
words++;
}
if (str[0] == ' ')
words--;
return words;
}
int countConsonant(string str, int consonant)
{
int length = str.length();
consonant = 0;
for (int i = 0; i < length; i++)
{
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' && str[i] != ' '&& str[i] != '1'
&& str[i] != '2' && str[i] != '3' && str[i] != '4' && str[i] != '5' && str[i] != '6'
&& str[i] != '7' && str[i] != '8' && str[i] != '9' && str[i] != '0')
consonant = consonant + 1;
}
return consonant;
}
the problem is changing i inside the loop (I guess you meant to change k):
if you did mean to set k, change i = rand() % length; into k = rand() % length;
also, your question is a variant of the permutation problem, which Fisher-Yates solves. I would suggest looking at it, you will probably get better "randomness" by using it.
You are mistakenly using the loop variable, i , twice here. Also you might want to seed the random number generator if you want truly random jumbling of the strings.
For an idiomatic way of doing this in c++ you can use the standard algorithms to do this as follows:
#include <iostream>
#include <algorithm>
#include <ctime>
#include <cstdlib>
int main(void){
srand ( unsigned ( time (NULL) ) );//seed the random shuffle
std::string test = "abcdef";
std::cout << "original string: " << test << std::endl;
std::random_shuffle(test.begin(),test.end());
std::cout << "shuffled string: " << test << std::endl;
return 0;
}
You are using i, j for your two random indices whereas these should be j, k.
It should be:
j = rand() % length;
k = rand() % length;
You are using i as loop variable but at the same time assign a random value to it within the loop.
A possible solution would be not to use two randoms at all but instead the iterating variable i itself [online example].
for(int i = 0; i < length; i++)
{
j = i + (rand() % (length-i));
char c = str[j];
str[j] = str[i];
str[i] = c;
}