I am very new to C++ and am trying to complete an assignment involving loops. The goal of the activity is to print "valid" for passwords not containing the character "S" and "invalid" for those that do.
Here's the code:
#include <iostream>
using namespace std;
int main() {
bool validPassword;
string codeWord;
int passLength;
cin >> codeWord;
passLength = codeword.length();
for (int i = 0; i <= passLength; ++i) {
if (codeWord.at(i) != 'S') {
validPassword = true;
continue;
}
else {
validPassword = false;
break;
}
}
if (validPassword) {
cout << "Valid" << endl;
}
else {
cout << "Invalid" << endl;
}
return 0;
}
I'm kinda new to c++ as well, but this code I made worked for it. I used 'codeWord.find()' instead of cycling through all of the characters in the string. Here is the code:
#include <iostream>
using namespace std;
int main() {
bool validPassword;
string codeWord;
cin >> codeWord;
if(codeWord.find("8") == string::npos) {
validPassword = true;
}
else{
validPassword = false;
}
if (validPassword) {
cout << "Valid" << endl;
}
else {
cout << "Invalid" << endl;
}
return 0;
}
Related
#include "../../std_lib_facilities.h"
bool CheckForDislike(vector<string> disliked, string slowo) {
int i = 0;
while (i < disliked.size()) {
if (slowo == disliked[i]) {
return true;
}
i++;
}
return false;
}
int main() {
cout << "Enter a word: ";
vector<string> disliked(2);
disliked[0] = "Szpinak";
disliked[1] = "Brokuły";
string slowo = "a";
while (cin >> slowo) {
if (CheckForDislike(disliked, slowo)) {
cout << "Biip\n";
}
else {
cout << slowo << '\n';
}
}
}
Above code should print "Biip" when you enter a word that is in disliked vector.
It doesn't work for words with signs like "ą","ł" basically special signs from my native language. The function returns 1 or true for them, so the problem has to be somewhere in conditional, but i cant see why.
I'll start by saying I have worked on this for 3 days now and this is only my second semester programming. I know this question is probably easy for most, but I really have very little experience.
The code I have written all works as intended except the invalid/blank entry validation. Anything I have found and tried just breaks other parts of the code or doesn't work at all.
Here are the instructions given in the homework for the part I am having issues with:
"Any invalid input for the menu will simply redisplay the menu.
Option 1 will prompt for a userName. An empty name will be ignored."
Here is my code. Any help is greatly appreciated.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<string> usernames;
void listMenu();
void addName();
void listNames();
void removeName();
int main()
{
char entry;
bool exit = false;
while (exit == false)
{
cout << "Choose from the following menu: \n";
listMenu();
cin >> entry;
if (entry == '\n')
{
listNames();
}
if (entry == '1')
{
addName();
}
else if (entry == '2')
{
listNames();
}
else if (entry == '3')
{
removeName();
}
else if (entry == 'x' || entry == 'X')
{
exit = true;
}
}
usernames.clear();
return 0;
}
void listMenu()
{
string menu[4] = { "1. Add a username","2. List all usernames","3. Delete a username","X. Exit" };
for (int i = 0; i < 4; i++) {
cout << menu[i] << endl;
}
}
void addName()
{
string name;
cout << "Enter a username: " << endl;
cin >> name;
usernames.push_back(name);
}
void listNames()
{
int n = 1;
cout << "**************\n";
for (auto& x : usernames)
{
cout << n <<". "<< x <<endl;
n++;
}
cout << "**************\n";
}
void removeName()
{
int x;
cout << "Which username would you like to remove?\n";
listNames;
cin >> x;
usernames.erase(usernames.begin()+x);
}
You can test your input and clear it if it's invalid. Using cin.fail, cin.clear and cin.ignore.
#include<iostream>
using namespace std;
bool cond;
int main() {
int n;
do {
cout << "Enter an integer number:";
cin >> n;
cond = cin.fail();
cin.clear();
cin.ignore(INT_MAX, '\n');
} while(cond);
return 0;
}
me again. I have a problem. I tried to run this code and when I compile it, the compiler shows no errors, but after running it, the program crashes. HELP!!!
What the program should do:
It searches trough the data of deseases and desease codes of the WHO ( World Health Organisation). Two csv files are given (english and german version) and you have a choice to search in english and in german. I think that the program chrashes when it tries to load the char*-s from the csv file.
It's driving me crazy.
Here is also the link where you can find the whole project:
LINK
Code:
#include <iostream>
#include <stdlib.h>
#include <cstring>
#include <iomanip>
#include <fstream>
#include <list>
#include <algorithm>
using namespace std;
enum KEY {code, disease} key;
enum LANGUAGE {english, deutsch} language;
char* buffer;
struct lst
{
char *_code;
char *_disease;
};
streamsize _buffer = 10000;
bool isPartOf(char* word, char* sentence)
{
unsigned int i=0;
unsigned int j=0;
for(;i < strlen(sentence); i++)
{
if(sentence[i] == word[j])
{
j++;
}
}
if(strlen(word) == j)
return true;
else
return false;
}
void printList(list<lst>* LST)
{
for(list<lst>::iterator i= LST->begin(); i != LST->end(); i++)
{
cout << i->_code << '\t' << i->_disease << endl;
}
}
list<lst>* makeList(char* fileName)
{
int i,j;
fstream ICDcsv;
ICDcsv.open(fileName);
list<lst>* new_list = new list<lst>;
if(ICDcsv.is_open())
{
while(ICDcsv)
{
lst* x = new lst;
ICDcsv.getline(buffer,_buffer);
i = 0;
j = 0;
while (buffer[i] != ';')
{
x->_code[i] = buffer[i];
i++;
}
i++;
while (buffer[i] != ';')
{
x->_disease[j] = buffer[i];
i++;
j++;
}
(*new_list).push_back(*x);
}
ICDcsv.close();
}
else{cerr << "Error: file error" << endl;}
return new_list;
}
list<lst>* listSearch(list<lst> *LST,char* wrd,KEY key)
{
switch(key)
{
case code:
for(list<lst>::iterator i = LST->begin(); i != LST->end(); i++)
{
if(!isPartOf(wrd, ( *i )._code))
{
delete [] i->_code;
delete [] i->_disease;
delete &(*i);
}
} //i->
break;
case disease:
for(list<lst>::iterator i = LST->begin(); i != LST->end(); i++)
{
if(!isPartOf(wrd, ( *i )._disease))
{
delete [] i->_code;
delete [] i->_disease;
delete &(*i);
}
}
break;
}
return LST;
}
int main()
{
int choice;
int program_end=1;
char* _file;
char* Search;
cout << "World Health Institution (WHO)/Weltgesundheitsorganisation" << endl;
cout << "International Statistical Classification of Diseases and Related Healt Problems (ICD)/Internationale statistische Klassifikation der Krankheiten und verwandter Gesundheitsprobleme" << endl;
cout << "1 english" << endl;
cout << "2 deutsch" << endl;
cout << "your choice/Ihre Auswahl: ";
cin >> choice;
cin.clear();
if(choice == 1)
language = english;
else
language = deutsch;
switch (language)
{
case english:
{
_file = "care_icd10_en.csv";
break;
}
case deutsch:
{
_file = "care_icd10_de.csv";
break;
}
}
cout << "0 end/Ende" << endl;
cout << "1 search for ICD code (e.g. K52.9)/Suche nach ICD Kode (Beispiel K52.9)" << endl;
cout << "2 search for desease (e.g. Ebola)/Suche nach Krankheit (Beispiel Ebola)" << endl;
cout << "your choice/Ihre Auswahl: ";
cin >> program_end;
cin.clear();
switch(program_end)
{
case 0: break;
case 1:
key = code;
cout << "to search for ICD code/zu suchender ICD Kode: ";
break;
case 2:
key = disease;
cout << "to search for deseade/zu suchende Krankheit: ";
break;
}
if(program_end != 0)
{
cin >> Search;
list<lst>* test = makeList(_file);
list<lst>* test2 = listSearch(test,Search,key);
printList(test);
}
return 0;
}
I have the following code below:
int main ()
{
char string[80];
bool Restart;
Restart = true;
while (Restart)
{
cout << "Enter a string\n" << endl;
cin.getline(string, 80);
cout << "\nYou entered: ";
printf(string, 80);
cout << endl;
int len=strlen(string);
bool flag = true;
for (int c=0; c!=len/2; c++)
{
if (flag)
{
if(string[c] != string[len-c-1])
{
flag = false;
}
}
else
{
break;
}
}
if (flag)
{
cout <<"\nThis is a Palindrome\n" << endl;
Restart = true;
continue;
}
else
{
cout << "\nThis is not a palindrome\n" << endl;
Restart = true;
continue;
}
cin.get();
}
}
I need to figure out a way to check if what the user entered is "END" in all caps, and if so, exit the program. I'm sure i can handle the exiting part, but I'm having trouble getting something that will check if the string entered is "END" in all caps.
Here is a solution that will terminate the while loop if "END" is entered. Create a helper method to do the parsing for END. Note this is very specific to the problem and not very reusable. It also is more difficult to maintain unlike Beta's solution, but you don't need to worry about maintenance until you start writing bigger programs.
bool Terminate(char* string, int len)
{
bool retval = false;
char* c = string;
if( 3 == len ) // "END\0"
{
if('E' == string[0])
{
if('N' == string [1])
{
if('D' == string[2])
{
retval = true;
}
}
}
}
return retval;
}
Then use it after int len=strlen(string); like so:
if(Terminate(string, len))
{
break; // Exit while loop
}
Make sure you declare Terminate before your main function
Is this enough of a hint?
#include <iostream>
int main()
{
char A[] = "END";
char B[10];
std::cin >> B;
std::cout << strcmp(A,B) << std::endl;
return(0);
}
So I know this is a pretty common error, but I'm very new to C++, we are using it for a programing languages class, and this error has me stuck. The delete parser; line is the line that causes this error, and I cannot figure out why.
Turtle2.cpp
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include "scanner.h"
#include "parser.h"
using namespace std;
int main(int argc, char* argv[]) {
//string line;
if (argc != 2) {
cout << "Usage: turtle filename" << endl;
return 0;
}
char* filename = argv[1];
cout << "filename is " << filename << endl;
ifstream in(filename);
Parser * parser = new Parser(&in);
AST* tree = parser->parse();
tree->evaluate();
delete tree;
delete parser; //This is the line that causes the error!
return 0;
}
parser.cpp
#include "parser.h"
#include "calcex.h"
#include <string>
#include <sstream>
Parser::Parser(istream* in) {
scan = new Scanner(in);
}
Parser::~Parser() {
try {
delete scan;
} catch (...) {
}
}
AST* Parser::parse() {
AST* returnValue = Prog();
cout << "We are still ok1" << endl;
return returnValue;
}
AST* Parser::Prog() {
AST* result = StmtList();
Token* t = scan->getToken();
if (t->getType() != eof) {
cout << "Syntax Error: Expected EOF, found token at column " << t->getCol() << endl;
throw ParseError;
}
cout << "We are still ok2" << endl;
return result;
}
AST* Parser::StmtList() {
AST* result = Statement();
Token* t = scan->getToken();
scan->putBackToken();
if (t->getType() != eof) {
AST* result = StmtList();
return result;
}
return result;
}
AST* Parser::Statement() {
float num1;
float num2;
stmtNode* node;
Token* t = scan->getToken();
/*if (turtle->getType() != keyword || turtle->getLex() != "turtle"){
cerr <<"expected turtle" << endl; //print to standard error stream
throw ParseError;
}*/
if (t->getType() == keyword && t->getLex() == "turtle"){
t = scan->getToken();
if (t->getType() == dot){
t = scan->getToken();
if (t->getType() == keyword && t->getLex() == "goto"){
t = scan->getToken();
if (t->getType() == lparen){
t = scan->getToken();
if (t->getType() == number){
istringstream in(t->getLex());
in >> num1;
t = scan->getToken();
if (t->getType() == comma){
t = scan->getToken();
if (t->getType() == number){
istringstream in(t->getLex());
in >> num2;
t = scan->getToken();
if (t->getType() == rparen){
cout << "Good" << endl;
node = new stmtNode(num1,num2);
cout << "X is " << node->getX() << endl;
cout << "Y is " << node->getY() << endl;
}
}
}
}
}
}
}
}
else{
cout << "bad" << endl;
}
return node;
}
scanner.cpp
#include "scanner.h"
#include "calcex.h"
#include <iostream>
#include <string>
using namespace std;
//Uncomment this to get debug information
//#define debug
const int numberOfKeywords = 2;
const string keywd[numberOfKeywords] = { //defining the keywords
string("turtle"), string("goto")
};
int isLetter(char c) { //c is bigger or equal to 'a' and small or equal to 'z'. same for captial versions
return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
}
int isDigit(char c) { //c is bigger or equal to '0' or smaller or equal to '9'
return (c >= '0' && c <= '9');
}
int isWhiteSpace(char c) { //c is a space, tab or newline
return (c == ' ' || c == '\t' || c == '\n');
}
Scanner::Scanner(istream* in): //scanner constructor
inStream(in),
lineCount(1),
colCount(0),
needToken(true),
lastToken(0)
{}
Scanner::~Scanner() { //scanner de-constructor
try {
delete inStream;
} catch (...) {}
}
void Scanner::putBackToken() { //method?
needToken = false;
}
Token* Scanner::getToken() { //method?
if (!needToken) {
needToken=true;
return lastToken;
}
Token* t;
int state=0;
bool foundOne=false;
char c;
string lex;
TokenType type;
int k;
int column, line;
c = inStream->get();
while (!foundOne) {
colCount++;
switch (state) {
case 0 :
lex = "";
column=colCount;
line = lineCount;
if (isLetter(c)) state=1;
else if (isDigit(c)) state=2;
else if (c=='.') state=3;
else if (c==',') state=4;
else if (c=='(') state=5;
else if (c==')') state=6;
else if (c=='\n') {
colCount=0;
lineCount++;
}
else if (isWhiteSpace(c));
else if (inStream->eof()) {
foundOne=true;
type=eof;
}
else {
cout << "Unrecognized Token found at line " << line <<
" and column " << column << endl;
throw UnrecognizedToken;
}
break;
case 1 :
if (isLetter(c) || isDigit(c)) state=1;
else {
for (k=0;k<numberOfKeywords;k++)
if (lex == keywd[k]) {
foundOne = true;
type = keyword;
}
if (!foundOne) {
type = identifier;
foundOne = true;
}
}
break;
case 2 :
if (isDigit(c)) state=2;
else {
type = number;
foundOne=true;
}
break;
case 3 :
type = dot;
foundOne = true;
break;
case 4 :
type = comma;
foundOne = true;
break;
case 5 :
type = lparen;
foundOne=true;
break;
case 6 :
type = rparen;
foundOne=true;
break;
}
if (!foundOne) {
lex = lex + c;
c = inStream->get();
}
}
inStream->putback(c);
colCount--;
if (type == number || type == identifier || type == keyword) {
t = new Token(type,new string(lex),line, column);
}
else {
t = new Token(type,new string(lex),line,column);
}
#ifdef debug
cout << "just found " << lex << " with type " << type << endl;
#endif
lastToken = t;
return t;
}
I don't know if that is enough code to help you guys out or not, if you need anything more just ask, its not a secret or anything :) I know its the de-constructor for parser, but I have no idea how to fix it, or really why this is happening... I've added scanner.cpp, because some ponited out that the problem could be in its deconstructor, so I hope that helps.
The reason why this is failing is that you are using delete on something that was allocated on the stack.
Note the combination of ifstream in(filename);, creating an ifstream on the stack and the delete inStream; in the destructor of Scanner.
The easiest suggestion would be to allocate in on the heap, whish ifstream *in = new ifstream(filename) or whatnot.
A better solution would probably be to have the other classes(Scanner, Parser, etc) take the ifstream by reference, and avoid pointers unless they are needed.
You are trying to delete a stack variable, in the destructor of Scanner.
Parser * parser = new Parser(&in);
Parser::Parser(istream* in) {
scan = new Scanner(in);
}
Parser::Parser(istream* in) {
scan = new Scanner(in);
}
Parser::~Parser() {
try {
delete scan;
} catch (...) {
}
}
Scanner::~Scanner() { //scanner de-constructor
try {
delete inStream;
} catch (...) {}
}