Hi I need help with some code. I need to test a function but I get a compiler error every time I try to compile. here's what I get, error: comparison between distinct pointer types 'void ()()' and 'const char' lacks a cast.
Here is my code.
#include <iostream>
using namespace std;
void getInput();
bool gameGoing = true;
int main()
{
do{
cout << "hello world this is a test.\n";
getInput();
if(getInput == "false")
{
return 0;
}
}while(gameGoing = true);
}
void getInput()
{
string userInput;
cin >> userInput;
}
Should probably be
#include <iostream>
using namespace std;
string getInput();
bool gameGoing = true;
int main()
{
do
{
cout << "hello world this is a test.\n";
if(getInput() == "false")
return 0;
} while(gameGoing == true);
}
string getInput()
{
string userInput;
cin >> userInput;
return userInput;
}
What I changed:
added a return type to the getInput function, so that the result of it doesn't get dismissed
fixed the if comparison to actually compare the result of getInput function againt the "false" value
fixed the while condition to compare the gameGoing with true value rather than overwriting it
Related
This is a simple function which will take value from user and if value is invalid then the function will call itself recursively until a valid input is provided.
#include<iostream>
using namespace std;
void getnum(){
int num;
string strnum;
getline(cin, strnum);
try{
num = stoi(strnum);
}
catch(invalid_argument &ia){
cout<<"Invalid argument\n";
getnum();
}
cout<<"\n"<<num;
}
int main(){
getnum();
return 0;
}
/*output(input: abc,abc,abc,4):
4
2494464
2494464
4201200
*/
Using the recursive approach the program is creating a new instance of the function every time an invalid argument is passed. After receiving a valid argument, function is printing multiple values(garbage values) of num due to multiple instances created.
The problem is that I want only the last value(correct one) to be printed. So I tried setting a 'flag' to control the execution of cout<<"\n"<<num.
#include<iostream>
using namespace std;
void getnum(){
int flag = 0;
int num;
string strnum;
getline(cin, strnum);
try{
flag = 1;
num = stoi(strnum);
}
catch(invalid_argument &ia){
flag = 0;
cout<<"Invalid argument\n";
getnum();
}
if(flag)
cout<<"\n"<<num;
}
int main(){
getnum();
return 0;
}
/*output(input:abc,abc,abc,4)
4 */
It solves my problem but still multiple instances are being created which I think is wastage of memory.
Is there any better way to do this without using a lot of memory(recursion)?
You get multiple outputs because you print outside "the happy path" - move printing inside the try block.
It's even clearer to put the entire "happy path" inside the try:
void getnum(){
try {
string strnum;
getline(cin, strnum);
int num = stoi(strnum);
cout<<"\n"<<num;
}
catch(invalid_argument &ia){
cout<<"Invalid argument\n";
getnum();
}
}
The idiomatic solution is to loop rather than recurse:
void getnum(){
while (true)
{
try {
string strnum;
getline(cin, strnum);
int num = stoi(strnum);
cout << "\n" << num;
return;
}
catch (invalid_argument &){
cout<<"Invalid argument\n";
}
}
}
hi guys so my question is how to convert a char array to a string. here is my code:
#include<iostream>
using namespace std;
int main()
{
while (true) {
char lol[128];
cout << "you say >> ";
cin.getline(lol,256);
cout << lol << endl;;
}
return 0;
}
so I want to convert lol to a string variable like "stringedChar" (if thats even english lol)
so I can do stuff like:
string badwords[2] = {"frick","stupid"};
for (int counter = 0; counter < 2;counter++) {
if(strigedChar == badwords[counter]) {
bool isKicked = true;
cout << "Inappropriate message!\n";
}
}
Sorry im just a c++ begginer lol
Do something like this :
as char lol[128];
into string like: std::string str(lol);
Line : cin.getline(lol,256); <--> should be changed to cin.getline(lol,128)
Just invoke std::getline() on a std::string object instead of messing about with a char array, and use std::set<std::string> for badwords as testing set membership is trivial:
#include <iostream>
#include <set>
#include <string>
static std::set<std::string> badwords{
"frick",
"stupid"
};
int main() {
std::string line;
while (std::getline(std::cin, line)) {
if (badwords.count(line) != 0) {
std::cout << "Inappropriate message!\n";
}
}
return 0;
}
Note that this tests whether the entire line is equal to any element of the set, not that the line contains any element of the set, but your code appears to be attempting to do the former anyway.
First off, you have a mistake in your code. You are allocating an array of 128 chars, but you are telling cin.getline() that you allocated 256 chars. So you have a buffer overflow waiting to happen.
That said, std::string has constructors that accept char[] data as input, eg:
#include <iostream>
using namespace std;
int main()
{
while (true) {
char lol[128];
cout << "you say >> ";
cin.getline(lol, 128);
string s(lol, cin.gcount());
cout << s << endl;;
}
return 0;
}
However, you really should use std::getline() instead, which populates a std::string instead of a char[]:
#include <iostream>
#include <string>
using namespace std;
int main()
{
while (true) {
string lol;
cout << "you say >> ";
getline(cin, lol);
cout << lol << endl;;
}
return 0;
}
That's the code:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main()
{
string name = "lol";
int score = 0;
vector<string>names;
vector<int>scores;
bool choose = true;
for (int l = 0; name != "stop"; ++l) {
cin >> name >> score;
if (name == names[l]) choose = false;
if (choose == true) {
names.push_back(name);
scores.push_back(score);
}
else cout << "error, name already used" << endl;
choose = true;
}
}
When I run the program, and I type a name followed by a score, it says: "debug assertion failed: vector subscription out of range".
Why? And how do I eliminate this error?
You try get element that doesn't exist. First you need push something to
vector<string> names;
or do check if names is empty:
if (!names.empty())
if(name == names[l])
choose = false;
also looking what you want achieve, it's seems that you have anyway wrong code, you only look at the last name you have added. So to help you a bit this solution works better:
int main()
{
string name;
vector<string> names;
while (cin >> name && name != "stop")
{
bool choose = true;
for (auto i : names)
{
if (name == i)
choose = false;
}
if (choose)
{
names.push_back(name);
}
else cout << "error, name already used" << endl;
}
}
I'm trying to test the casting of a string to an integer to make sure the data in the string is actually data that belongs in an integer. (ex. the user input '!!!!' so I don't want it going to the int).
The problem I'm having is I want to be able to throw an error somehow right after I detect that the conversion can't happen. The reason I want to test it during the cast or right after is because I need the input from the user to first go to a string.
I first tried doing "option 1" and I noticed that some sort of a debug error pops up and it doesn't let me throw my own and show a more user friendly error.
I then am trying option 2 (thinking I could wrap the verify right around the cast) but while I'm Watching the variable type, it passes option 2 even though it's showing as a string and my code doesnt seem to catch that it's not an int, and therefore throw my error
I would only use one of the two options and note both obviously. I just put both of my e
using namespace std;
#include <string>
#include <iostream>
#include <typeinfo>
int main()
{
string employeeNumber;
string hoursWorked;
int newEmployeeNumber;
cout << "What is your employee number?" << endl;
cin >> employeeNumber;
//CONVERT AND VERIFY CAST/CONVERSION OCCURRED SUCCESSFULLY
//IF NOT (ex. user entered '!!!' so it shouldnt be able to cast to int..
//THEN THROW MY ERROR
//option 1
newEmployeeNumber = stoi(employeeNumber);
throw MyErrorThatDoesntGetReached("notan int");
//(will throw its own error right there and I can't let it throw mine after
//option 2
if (typeid(stoi(employeeNumber)) != typeid(int) )
throw Exception("data in file is CORRUPT");
}
Sleeper's idea isn't bad at all. Alternatively though, we could just catch the exception that std::stoi() throws on invalid inputs:
#include <string>
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
string employeeNumber;
string hoursWorked;
int newEmployeeNumber;
cout << "What is your employee number?" << endl;
cin >> employeeNumber;
try {
newEmployeeNumber = stoi(employeeNumber);
} catch (std::invalid_argument const & e) {
throw MyException("The input couldn't be parsed as a number");
} catch (std::out_of_range const & e) {
throw MyException("the input was not in the range of numbers supported by this type");
}
}
For testing a value I offer regular expression:
#include <string>
#include <conio.h>
#include <iostream>
#include <typeinfo>
#include <regex>
using namespace std;
bool isNumber( string val );
void main() {
string employeeNumber;
string hoursWorked;
int newEmployeeNumber;
cout << "What is your employee number?" << endl;
cin >> employeeNumber;
if ( isNumber( employeeNumber ) ) {
newEmployeeNumber = stoi(employeeNumber);
cout << "is number\n";
}
else {
cout << "is not number\n";
}
getch();
}
bool isNumber( const string val ) {
std::string templ("\\d*");
if ( regex_match( val, std::regex(templ) ) ) {
return true;
}
return false;
}
UPDATE:
Other variant of function IsNumber:
bool isNumber( const string val ) {
for( int i = 0; i < val.length(); i++ ) {
if ( !isdigit( val[i] ) ) {
return false;
}
}
return true;
}
I have this code:
#include <iostream>
#include <string>
#include "header8.h"
using namespace std;
int main()
{
Counter test;
string input;
cout << "Enter a string\n";
getline(cin, input);
test.countcharacters();
test.countnumbers();
}
void Counter::countcharacters(){
for(unsigned int i=0; i<input.length(); i++){
if(input.at(i) == 'a'){
alphabet[0]++;
}
}
}
void Counter::countnumbers(){
for(unsigned int i;i<input.length();i++){
if(input.at(i) == '0'){
numbers[i]++;
}
}
}
My error:
When I enter my string, the value always returns 0. Any idea why?
Post your Counter class definition
As one of the comments correctly stated, I can see no way counter sees the same input var.
Edit: then based on your code the fix should be
replace in main
getline(cin, input);
with
getline(cin, test.input);
and remove
string input;
Here is my solution.
int main()
{
string input;
cout << "Enter a string\n";
getline(cin, input);
Counter test(input); // highlight
test.countcharacters();
test.countnumbers();
}
You need to call the constructor of class Counter and transfer 'input' to Counter::input (of course, you need to add a constructor with a string as the parameter). Or you can write a function as below:
void Counter::setInput(string _input)
{
this.input = _input;
}
and call this function before you start counting.