Preventing user from inputting certain chars in c++ [closed] - c++

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'm quite new to c++ so please understand that my question may be silly.
I need to create a function which takes from the user a table and fills it with only specific characters. Let's say that the user needs to input his name. If the user inputs a charater from A to Z (or a to z) the character should be displayed on the screen and in that case- everything is fine. The problem is- when the user inputs a forbidden character (for instance 1-9) this shouldn't be displayed on the screen and the cursor should stay in the same position).
Do you guys know how to do this?

May be you can use this to do your job:
char ch;
while(ch = getch())
{
if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
{
cout << ch;
}
}
This will print only [A-Z][a-z]. You can also store your required char to use further.

On Windows you can use conio.h.
Also, you can overload the istream::operator>> function to make solution more elegant and easy to use:
Complete example:
#include <iostream>
#include <conio.h>
using namespace std;
struct person_t
{
string name;
string last_name;
};
// This is the function you're looking for.
void get_filtered_string(string &str)
{
char c;
str = "";
do
{
c = _getch();
if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'))
{
putchar(c); // 1
str.push_back(c);
}
} while (c != '\r'); // 2
}
istream &operator>>(istream &stream, person_t &person)
{
string str = "";
cout << "Enter name: ";
get_filtered_string(str);
person.name = str;
cout << endl;
cout << "Enter last name: ";
get_filtered_string(str);
person.last_name = str;
cout << endl;
return stream;
}
int main()
{
person_t person;
cin >> person;
cout << person.name.c_str() << " " << person.last_name.c_str() << endl;
return 0;
}
Output character to screen.
In Windows when you hit Enter you're introducing two characters '\r' and '\n' in that order. Thats why we check here for '\r'.

Related

Element counting issue [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
#include <iostream>
using namespace std;
int countLetters(char text[], char letter);
int main()
{
char letter;
cout << "Enter a letter: ";
cin >> letter;
cin.ignore();
char text[1024];
cout << "Enter text: ";
cin.getline(text, 1024);
int letterCount = countLetters(text, letter);
cout << "Number of '" << letter << "'s: " << letterCount << endl;
return 0;
}
int countLetters(char text[], char letter)
{
int letterCount = 0;
for (int i = 0; i <= text[i]; i++)
{
if (letter == text[i])
letterCount++;
}
return letterCount;
}
This code, as written, is designed to ask the user for, first, the letter they want to search for in a line of text. Second, it will ask the user to input the line of text they want to have searched. Finally, it will spit out how many letters there are in the specific line of text they input.
My specific error lies here: when user asks for 'e' in "CS 124 - Introduction to Software Development", program only declares that there is one 'e' . I'm unsure what's wrong, because when you run the program and input 'o' while asking to search the exact same line of text, you get the proper number of 'o' values returned, 4.
Any ideas as to what my error is and why it glitches when searching for 'e' ?
Your for condition is wrong, the for loop should continue while i is less than text's length not the value of text[i]. Since this is C++ you should use strings not character arrays, why make it harder on yourself?
The code below is a C++ approach, note that my C++ is a bit rusty and the code might contain errors.
#include <iostream>
#include <string>
using namespace std;
int countLetters(string text, char letter);
int main() {
char letter = ' ';
string text;
cout << "Enter a letter: ";
cin >> letter;
cin.ignore();
cout << "Enter text: ";
getline(cin, text); // use 'getline(cin, text)' instead of 'cin >> text'
int letterCount = countLetters(text, letter);
cout << "Number of '" << letter << "'s: " << letterCount << endl;
return 0;
}
int countLetters(string text, char letter) {
int letterCount = 0;
for (int i = 0; i < text.size(); i++) {
if (letter == text[i]) {
letterCount += 1;
}
}
return letterCount;
}
change the condction
i <= text[i]
to
text[i] != '\0'

Un-mash a string in C++ using recursion [closed]

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 6 years ago.
Improve this question
Part A: Have a user input a string. Then display this string smashed up as follows: display the first character in the string, then the last, then the second, then the second to last, then the third... So if the string is “abcdef”, it will display:
afbecd (input “abcdef”)
12345 --> 15243
123456 --> 162534
Part B: Now, unmash the above strings.
i.e 162534 -->123456
I got part A to work.
#include <iostream>
using namespace std;
void mash(string s);
int main()
{
string sequence;
cout << "Enter a sequence: ";
getline(cin, sequence);
mash(sequence);
}
void mash(string s)
{
int a = s.length();
if (a == 0)
{
return;
}
if (a == 1)
{
cout << s;
return;
}
cout << s[0];
if(a>1)
{
cout << s[a - 1];
s = s.substr(1,a-2);
mash(s);
}
}
but I have no clue how to approach part B. I guess I can try to print out the characters in the even position, say in the string 162534, thus I will get 123. Then I guess I can try to print out the odd position characters from the last one up to the first one, i.e, 456. Combining these two will get the original strings but I have no clue how to use recursion to solve part B.
Here is a hint. So unmash(string s) should first print the first character s[0], then unmash(s.substr(2, length - 2)), then s[1]. Of course, you also need to check if length <= 2 need to treat that differently.
Here is my answer an it works perfectly thanks to all of the members of SO who helped me.
#include <iostream>
using namespace std;
void unmash(string s);
int main()
{
string sequence;
cout << "Enter a sequence: ";
getline(cin, sequence);
unmash(sequence);
}
void unmash(string s)
{
int a = s.length();
if (a == 0)
{
return;
}
if (a == 1||a == 2)
{
cout << s;
return;
}
cout << s[0];
if(a>1)
{
unmash(s.substr(2));
cout << s[1];
}
}

error when calling char to allow user to enter choice [closed]

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 6 years ago.
Improve this question
I am writing a simple text game in C++. The user has the option of choosing the left room or the right room. I did have this set up as an int statement: enter 1 for left, enter 2 for right. Now I would like to have the user enter left for left room, right for right room.
I replaced the int with char, but I am getting an error.
#include <iostream>
using namespace std;
int main() {
char decision;
cin >> decision;
if (decision == left) {
cout << "went left" << endl;
}
return 0;
}
Error: comparison between pointer and integer
char stands for a single character - what you need is a string (multiple characters).
when you actually have the user's value in decision you need to compare it to the string "left" rather than just left which the compiler tries to interpret as a symbol (like a variable name).
All in all:
#include <iostream>
#include <string>
using namespace std;
int main() {
string decision;
cin >> decision;
if (decision == "left") {
cout << "went left" << endl;
}
return 0;
}
the easiest way use strcmp:
#include <iostream>
int main()
{
char decision[50] = "";
std::cout << "Decision: ";
std::cin.get(decision, 50, '\n');
if( !(strcmp(decision, "left")) )
std::cout << "left";
else
if( !(strcmp(decision, "right")) )
std::cout << "right";
else
std::cout << "bad input!" << std::endl;
std::cout << std::endl;
return 0;
}
you should also make no difference between lowercase and uppercase because if a user enters "Left" instead "left" then it won't work

How do I get out of this do-while loop? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm trying to create a program that intakes a string of characters, verifies it, then sorts it and prints it out.
I'm sure there is a glaring logic error in here somewhere, can someone help point it out? I've spent hours staring at my screen. I tried everything I know in my limited knowledge of C++, but I still can't get the thing working.
Anything you can offer will help me in some way, even if it's condescending.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void mySort(string &s);
int main()
{
string str;
char c;
bool invalid = true;
cout<<"Please enter some alphabetical characters:"<<endl;
cout<<"(* to end input): ";
do
{
getline(cin, str, '*');
for(int i = 0; i < str.length(); i++)
{
c = str.at(i);
}
if(! ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ) )
{
cout<<"Error!"<<endl;
}
else
{
(invalid==false);
cout<<"You entered: "<<str<<endl;
mySort(str);
}
} while(invalid==true);
system("PAUSE");
return(0);
}
void mySort(string &s)
{
sort(s.begin(), s.end());
cout<<"The string after sorting is: "<<s<<endl;
}
I'm almost sure the problem with the verification lies in this line:
if(! ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) ) )
I'm sure my bools are wrong as well.
Anything, anything at all, I've wasted several hours of my life banging my head against the wall because of this.
You never set invalid to anything but true.
This line:
(invalid==false);
should be:
invalid = false;
The former version compares invalid to false, then throws away the result of the comparison. Nothing changes.
(invalid==false); Should be invalid=false;
First change:
(invalid == false);
invalid = false;
As others have said, you are not assigning the invalid variable correctly. You are also not validating the input string correctly, either. You loop through the entire string, and then validate only the last character seen, rather than validating each character while looping.
I would suggest re-writing the loop to get rid of the invalid variable and fix the validation, eg:
int main()
{
string str;
char c;
do
{
cout << "Please enter some alphabetical characters:" << endl;
cout << "(* to end input): ";
if (!getline(cin, str, '*'))
break;
if (str.empty())
cout << "You did not enter anything!" << endl;
else if (str.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") != string::npos)
cout << "Error! Bad input" << endl;
else
{
cout << "You entered: " << str << endl;
mySort(str);
break;
}
}
}
while (true);
system("PAUSE");
return 0;
}

Reverse each character in a string except special characters (e.g. "?") [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
For example : how are you? ----> woh era uoy?
This is my code, i got it worked but the question mark is besing reversed too.
How can i make it remained intact?
#include <iostream>
using namespace std;
int main()
{
string ch;
while(cin >> ch)
{
for(int i = ch.length() - 1; i >= 0; i--)
{
cout << ch[i];
}
cout << " ";
}
return 0;
}
Your chosen input method (cin >> ch) automatically splits the input into separate words.
Like Jerry Coffin said in his answer, you have to skip over punctuation etc to find to alpha characters to swap. Roughly like this:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string ch;
while (cout << "String? " && cin >> ch)
{
cout << "Input: <<" << ch << ">>\n";
const char *bp = ch.c_str();
const char *ep = ch.c_str() + ch.length() - 1;
const char *sp = ch.c_str();
while (sp < ep)
{
while (sp < ep && (*sp != ' ' && !isalpha(*sp)))
sp++;
while (sp < ep && (*ep != ' ' && !isalpha(*ep)))
ep--;
char c = *sp;
ch[sp-bp] = *ep;
ch[ep-bp] = c;
sp++;
ep--;
}
cout << "Output: <<" << ch << ">>\n";
}
cout << endl;
return 0;
}
Sample dialogue
String? How are you?
Input: <<How>>
Output: <<woH>>
String? Input: <<are>>
Output: <<era>>
String? Input: <<you?>>
Output: <<uoy?>>
String? Pug!natious=punctuation.
Input: <<Pug!natious=punctuation.>>
Output: <<noi!tautcnu=psuoitanguP.>>
String?
You can tweak it from here. I'm far from claiming this is idiomatic C++; the use of const char * in the middle shows my C background.
Start from the beginning of the string, and scan forward until you find a letter. The scan backwards from the end until you find a letter. Swap them. Continue until the two positions meet.
Note: above I've used "letter", but all I really mean is "one of the characters that should be reversed." You haven't defined very precisely which characters should be swapped and which shouldn't, but I'm assuming you (or your teacher) has a reasonably specific definition in mind.
Try using array and scanning each letter to see if there is a question mark. If there is, move it to the last place of the array.
simple solution or hack to solve this case alone. if there are more cases comment it lets solve it together.
#include <iostream>
using namespace std;
int main()
{
string ch;
while(cin >> ch)
{
int flag = 0;
for(int i = ch.length() - 1; i >= 0; i--)
{
if(ch[i] != '?')
cout << ch[i];
else
flag = 1;
}
if(flag)
cout << "?";
else
cout << " ";
}
return 0;
}