The valid charaters are
// ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/
#include <iostream>
#include <string>
using namespace std;
int main();
{
bool bIsValid = true;
// test characters
string strCheck("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/");
string s("foo#?+baa") ; // should bring a "false" because of the "#?+" characters
string::const_iterator it = strCheck.begin();
// this is NOT a clever soulution has anybody a better idea ?
while (s.find(*it) != string::npos)
{
++it;
if(!s.find((*it))
{
bIsValidKey = false;
break;
}
}
cout << "Is Valid: " << bIsValid << endl ;
}
My problem is how can a get the first charater after the iteratorpoint to compare
with the allowed charactes. I need something like (*it).first_charater_after to
solve the problem.
Dos anybody has an other idea to check that in the string only exists a defined
number of charaters?
Use string::find_first_not_of?
Try this:
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
bool bIsValid = true;
string s("GHHbaa111__") ; // Add/remove other characters
regex r("^[[:alnum:]_]*$");
if (regex_match(s,r)) {
cout << "Valid string" << endl;
} else {
cout << "Invalid string" << endl;
}
}
#include <iostream>
#include <string>
int main() {
bool bIsValid = true;
// test characters
std::string strCheck("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/");
std::string s("foo#?+baa") ; // should bring a "false" because of the "#?+" characters
if (s.find_first_not_of(strCheck) != std::string::npos)
bIsValid = false;
std::cout << "Is Valid: " << bIsValid << std::endl ;
}
Related
Goal: Android/iOS app that displays tricky-to-spell words when user puts in a letter.
The code runs correctly, except for non-English characters. The program allows some non-English curse words through when the user puts in their first name.
Expected result: Program will reject all curse words (within
nameCurseWordsList.txt)
Actual result: Some non-English curse words are let through.
Error messages: None
Tried:
Changing vector input and the related variable, userFirstName, to wstring.
Checked to see if VS2019 settings were set to "Autodetect UTF-8 encoding without signature" - Already enabled.
Changed encoding of nameCurseWordsList.txt from "UTF-8 with BOM" to "UTF-8".
Set VS2019's cmd output window to use the font Lucida Console.
How to handle unicode character sequences in C/C++?
How can my program switch from ASCII to Unicode?
How to show Unicode characters in Visual Studio?
Code:
// Description: Android/iOS application that takes in a letter and displays tricky-to-spell words.
#include <iostream>
#include <fstream>
#include <locale>
#include <string>
#include <vector>
#include <limits>
#include <sstream>
#include "usingDeclarations.hpp"
vector <string> trickyWordsVector;
vector <wstring> nameCurseWordsVector;
void printWords(char userLetterInput);
void getTrickyWords();
void getNameCurseWords();
int main() {
cout << "----------------<>-----------\n";
cout << "Welcome to Your TRICKY WORDS Helper!\n";
cout << "----------------<>-----------\n";
wstring userFirstName;
size_t firstNameOnlyAlpha{};
bool isNameCurseWord = false;
do {
cout << "\nEnter your first name: ";
getline(wcin, userFirstName);
for (unsigned __int8 i = 1; i < userFirstName.length(); i++) {
if (userFirstName[i - 1] == ' ') {
userFirstName[i] = toupper(userFirstName[i]);
} else {
userFirstName[i] = tolower(userFirstName[i]);
}
}
userFirstName[0] = toupper(userFirstName[0]);
firstNameOnlyAlpha = userFirstName.find_first_of(L"0123456789`~!##$%^&*()':'';''/'-_=+{}[]|:<>,.' '?'\t\"");
getNameCurseWords();
if (find(nameCurseWordsVector.begin(), nameCurseWordsVector.end(), userFirstName) != nameCurseWordsVector.end()) {
cout << "Curse word entered. Please freakin' try again.\n";
isNameCurseWord = true;
} else {
isNameCurseWord = false;
}
} while (isNameCurseWord || firstNameOnlyAlpha != string::npos || userFirstName.empty());
char userLetterInput;
char userChoiceContinue;
do {
do {
cout << "\nEnter a letter [a-z]: ";
cin >> userLetterInput;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
userLetterInput = toupper(userLetterInput);
if (isalpha(userLetterInput)) {
wcout << "\nHey " << userFirstName << ",\n\nHere's your list of tricky words for the letter (" << char(toupper(userLetterInput)) << "):\n" << endl;
}
} while (!isalpha(userLetterInput));
getTrickyWords();
printWords(userLetterInput);
do {
cout << "\nWould you like to enter another letter [y,n]?: ";
cin >> userChoiceContinue;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} while (char(tolower(userChoiceContinue)) != 'y' && char(tolower(userChoiceContinue)) != 'n');
} while (char(tolower(userChoiceContinue)) == 'y');
cout << "\n----------------<>-----------\n";
cout << "Thank you for using Your TRICKY WORDS Helper!\n";
cout << "\n----------------<>-----------\n";
return 0;
} // end main()
void printWords(char userLetterInput) {
for (int i = 0; i < trickyWordsVector.size(); i++) {
if (trickyWordsVector[i][0] == userLetterInput) {
cout << trickyWordsVector[i];
cout << "\n";
}
}
} // end printWords()
void getTrickyWords() {
ifstream trickyWordsFile("trickyWordsList.txt");
if (trickyWordsFile.is_open()) {
if (trickyWordsVector.empty()) {
string line;
while (getline(trickyWordsFile, line)) {
if (line.size() > 0) {
trickyWordsVector.push_back(line);
}
}
}
}
else {
cerr << "Cannot open the file.";
}
trickyWordsFile.close();
} // end getTrickyWords()
void getNameCurseWords() {
wifstream nameCurseWordsFile("nameCurseWordsList.txt");
if (nameCurseWordsFile.is_open()) {
if (nameCurseWordsVector.empty()) {
wstring line;
while (getline(nameCurseWordsFile, line)) {
if (line.size() > 0) {
nameCurseWordsVector.push_back(line);
}
}
}
}
else {
cerr << "Cannot open the file, you sailor mouth. ;)";
}
nameCurseWordsFile.close();
} // end getNameCurseWords()
usingDeclarations.hpp
#pragma once
using std::cout;
using std::wcout;
using std::cin;
using std::wcin;
using std::cerr;
using std::getline;
using std::endl;
using std::use_facet;
using std::numeric_limits;
using std::streamsize;
using std::string;
using std::wstring;
using std::ifstream;
using std::wifstream;
using std::vector;
using std::locale;
using std::ctype;
trickyWordsList.txt or trickyWordsFile
Argument
Atheist
Axle
Bellwether
Broccoli
Bureau
Caribbean
Calendar
Camaraderie
Desiccate
Desperate
Deterrence
nameCurseWordsList.txt or nameCurseWordsFile (partial list)
// Irish
RáIcleach
// German
ScheißKopf
// Russian
Oбосра́ться
Obosrat'sya
// Chinese
王八蛋
Hùn Zhàng
// Japanese
くそ
// Korean
아, 씨발
Thanks for any advice.
Run code using https://repl.it/~
I want compare if both sequence are equals and i'm using the following code but comparation always return false.
=========================================================================
// testecompare.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>
#include <Windows.h>
using namespace std;
string getCurrentDirectoryOnWindows()
{
const unsigned long maxDir = 260;
char currentDir[maxDir];
GetCurrentDirectory(maxDir, currentDir);
strcat(currentDir, "\\l0gs.txt");
return string(currentDir);
}
string ReadFileContent() {
string STRING;
string aux;
ifstream infile;
infile.open(getCurrentDirectoryOnWindows());
while (!infile.eof())
{
getline(infile, STRING);
return STRING;
}
infile.close();
return "";
}
int _tmain(int argc, _TCHAR* argv[])
{
char str[MAXCHAR] = "";
sprintf(str, "0x0%X", "1D203E5");
cout << str << endl;
cout << "File content: " << ReadFileContent() << endl;
// if i have the string "0x01D203E5" in my txt file
if (_stricmp(str,ReadFileContent().c_str()) == 0) {
cout << "Contents are equals!\n";
}
system("pause");
return 0;
}
How make this comparation correctly?
Thank you very much.
An easy trick for comparing instances of different types is to convert them to a common type then compare.
So for example:
std::string content(ReadFileContent());
std::string from_array(str)
if (from_array == content)
{
}
Edit 1: Working example
The code works.
Here is a working program:
#include <iostream>
#include <string>
int main()
{
static const char text[] = "Hello";
std::string text_as_string(text);
std::string expected_str("Hello");
if (text_as_string == expected_str)
{
std::cout << "Strings are equal: " << text_as_string << "\n";
}
else
{
std::cout << "Strings are not equal.\n";
}
return 0;
}
$ g++ -o main.exe main.cpp
$ ./main.exe
Strings are equal: Hello
Remember, the above code samples are compare entire or whole strings, not substrings. If you want to search for a key string within a larger string, that requires different functions.
Here's all the code
#include <iostream>
#include <string>
#include <windows.h>
#include <stdlib.h>
using namespace std;
void Pdelay(string str)
{
for (char c : str)
{
std::cout << "" << c << "";
Sleep(100);
}
std::cout << '\n';
}
int main()
{
int exit = 1;
while (exit == 1)
{
cout<< "Type something\n:";
string str;
str.clear();
getline(cin,str);
Pdelay(str);
cout << "\n\n[1]Type something again"<< endl;
cout << "[2]Exit\n:";
cin >> exit;
}
return 0;
}
Whenever I run it, it works properly the first time round, when it loops back it skips the getline and continues with the two cout statements.
Immediately after you use cin, the newline remains in the buffer and is being "eaten" by the subsequent getline. You need to clear the buffer of that additional newline:
// immediately after cin (need to #include <limits>)
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
That's why it's not a very good idea to combine std::cin and std::getline. BTW, you can write your code in fully standard compliant C++11, with no additional non-library headers:
#include <chrono>
#include <iostream>
#include <limits>
#include <string>
#include <thread>
void Pdelay(std::string str)
{
for (char c : str)
{
std::cout << "" << c << "" << std::flush;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
std::cout << '\n';
}
int main()
{
int ext = 1;
while (ext == 1)
{
std::cout << "Type something\n:";
std::string str;
str.clear();
std::getline(std::cin, str);
Pdelay(str);
std::cout << "\n\n[1]Type something again" << std::endl;
std::cout << "[2]Exit\n:";
std::cin >> ext;
if(!std::cin) // extraction failed
{
std::cin.clear(); // clear the stream
ext = 1;
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
}
I just realized that this question has been asked (in a slightly modified form) before, and the answers are great:
Why does std::getline() skip input after a formatted extraction?
Beginner C++ student here, first ever programming class. I am trying to put together a program that will identify if a string is all lower case or not. I got as far as the code below. However, I need to account for spaces " ". If there is a space in the string that is input by the user, the program is suppose to return that it is not all lower case. Example:
input: abc def
return: The string is not lower case.
Would any of you ever so kindly advise what would be the best way to account for this in the code below?
NOTE: I know I have 'included' some extra header files, but that is because this is going to be part of another program and this is just an excerpt to get things running.
Thank you so very much all!!
#include <fstream>
#include <iostream>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <cctype>
#include <iomanip>
using namespace std;
bool die(const string & msg);
bool allLower(const string & l);
int main() {
string l;
cout << "\nEnter a string (all lower case?): ";
cin >> l;
if (allLower(l) == true)
{
cout << "The string is lower case." << endl;
}
else
{
cout << "The string is not lower case." << endl;
}
}
bool allLower(const string & l) {
struct IsUpper {
bool operator()(int value) {
return ::isupper((unsigned char)value);
}
};
return std::find_if(l.begin(), l.end(), IsUpper()) == l.end();
}
bool die(const string & msg){
cout << "Fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
You could use a good old fashion for-loop.
bool allLower(const std::string & l)
{
for(unsigned int i = 0; i < l.size(); i++)
{
if(l[i] == ' ')
{
return false;
}
else if(isalpha(l[i]))
{
if(isupper(l[i]))
return false;
}
}
return true;
}
Note that if you feed it in something like "2" it will return true. You could add a final else statement that returns false if you so desire.
You can check to see if a character is alphabetic using the function std::isalpha() prior to using std::isupper() or std::islower() to checking whether all letters within your string are uppercase/lowercase, etc
A range-based for loop would be clearer than indices IMO
bool allLower(const std::string &l)
{
for (auto c : l)
{
if ((c == ' ') ||
(std::isalpha(c) && std::isupper(c)))
{
return false;
}
}
return true;
}
From the following code, I expect to get this output from the corresponding input:
Input: FOO Output: Match
Input: FOOBAR Output: Match
Input: BAR Output: No Match
Input: fOOBar Output: No Match
But why it gives "No Match" for input FOOBAR?
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;
int main ( int arg_count, char *arg_vec[] ) {
if (arg_count !=2 ) {
cerr << "expected one argument" << endl;
return EXIT_FAILURE;
}
string InputString = arg_vec[1];
string toMatch = "FOO";
const regex e(toMatch);
if (regex_match(InputString, e,match_partial)) {
cout << "Match" << endl;
} else {
cout << "No Match" << endl;
}
return 0;
}
Update:
Finally it works with the following approach:
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <boost/regex.hpp>
using namespace std;
using namespace boost;
bool testSearchBool(const boost::regex &ex, const string st) {
cout << "Searching " << st << endl;
string::const_iterator start, end;
start = st.begin();
end = st.end();
boost::match_results<std::string::const_iterator> what;
boost::match_flag_type flags = boost::match_default;
return boost::regex_search(start, end, what, ex, flags);
}
int main ( int arg_count, char *arg_vec[] ) {
if (arg_count !=2 ) {
cerr << "expected one argument" << endl;
return EXIT_FAILURE;
}
string InputString = arg_vec[1];
string toMatch = "FOO*";
static const regex e(toMatch);
if ( testSearchBool(e,InputString) ) {
cout << "MATCH" << endl;
}
else {
cout << "NOMATCH" << endl;
}
return 0;
}
Use regex_search instead of regex_match.
Your regular expression has to account for characters at the beginning and end of the sub-string "FOO".
I'm not sure but "FOO*" might do the trick
match_partial would only return true if the partial string was found at the end of the text input, not the beginning.
A partial match is one that matched
one or more characters at the end of
the text input, but did not match all
of the regular expression (although it
may have done so had more input been
available)
So FOOBAR matched with "FOO" would return false.
As the other answer suggests, using regex.search would allow you to search for sub-strings more effectively.