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
Related
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 3 years ago.
Improve this question
I'm trying to make a login page. When the program starts, the user has to type Guest and Password 1234 and he can edit his/her account. However, when I try to run it, it says:
Line 15 "Error incompatible types in assignment of 'const char[6]' to 'char[20]'
Line 16 "Error incompatible types in assignment of 'const char[5]' to 'char[20]'
I think it has to do with pointers but I am still a c++ newbie so I am having a hard time to understand pointers
#include <iostream>
#include <cstring>
#include <stdio.h>
#include <string.h>
using namespace std;
const int LINE_LENGTH=20;
const int ID_LENGTH=8;
struct profile{char user[20];char password[20];double CGPA; int ID;};
int main(){
int count=0, i;
profile student[10];
student[0].user="Guest"; //Line 15
student[0].password="1234"; //Line 15
char signupName[20];
char signupPassword[20];
while (count==0)
{
cout << "#############################################\n";
cout << " Welcome to my program! \n";
cout << " Sign up to get started \n\n\n";
cout << " If you are starting, use username 'Guest' \n";
cout << " and password '1234' \n\n";
cout << "Username: ";
cin >> signupName;
cout << "Password: ";
cin >> signupPassword;
cout << "#############################################\n";
for (i=0;i<11; i++)
{
if(strcmp(signupName,student[i].user)==0 && strcmp(student[i].password,signupPassword)==0)
{
count++;
}
}
if(count==0)
{
system("cls");
cout<<"Your username and/or password is incorrect\n";
}
}
system("cls");
}
You need two minor changes to your code! First, as Francois Andrieux says, you can't assign char array strings with = ...
// student[0].user = "Guest";
// student[0].password = "1234";
strcpy(student[0].user, "Guest");
strcpy(student[0].password, "1234");
Second, your for loop runs once to often:
// for (i = 0; i < 11; i++)
for (i = 0; i < 10; i++) // Note: The last element in an array of 10 is x[9]!
This question already has answers here:
cin input (input is an int) when I input a letter, instead of printing back incorrect once, it prints correct once then inc for the rest of the loop
(2 answers)
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 4 years ago.
I've been coding in C++ for all of a few days, so please talk to me like I'm a baby. With that out of the way,
I've made a short algorithm that asks a set of questions (to be answered 0 for no and 1 for yes) and stores the user's answer as an integer. Everything works as expected as long as the user only inputs integers (or, in one case, a string with no spaces).
But if the input doesn't match the variable type, the program immediately outputs this infinite loop that appears later in the program. That loop is supposed to print a question, wait for input, and then ask again if the answer isn't '1', but in the failure state it just prints the question without end. I can't see any reason why the previous questions would be connected to this. It doesn't happen on the questions that come after it, if that's a clue.
Here's a pared-down version of my code with, I hope, all the important information intact:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int answer1;
string answer1C;
int answer2;
int answer2B;
int score;
score = 0;
cout << "Question 1" << endl;
cin >> answer1;
if (answer1 == 1)
{
++score;
//some other questions go here
cout << "Question 1C" << endl;
cin >> answer1C;
if (answer1C.size() == 6)
{
++score;
}
}
cout << "Question 2" << endl;
cin >> answer2;
if (answer2 == 0)
{
cout << "Question 2B" << endl;
cin >> answer2B;
if (answer2B == 0)
{
--score;
}
while (answer2B != 1) //Here is the infinite loop.
{
cout << "Question 2B" << endl;
cin >> answer2B;
}
}
cout << "Question 3" << endl;
//and so on
return 0;
}
I would love to have it accept any input and only perform the ensuing steps if it happens to meet the specified conditions: for instance, in question 1.2, it only awards a point if the answer is a string of length 6, and otherwise does nothing; or in question 2.1, it repeats the question for any input that isn't '1', and moves on if it is.
But in any case whatsoever, I need it to do something else when it fails. Please help me figure out why this is happening. Thank you.
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 7 years ago.
Improve this question
Why can't compare two strings in if condition?
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string sexo[20], feminino;
feminino = "f";
for (int i = 0; i < 3; i++) {
do {
cout << endl << "enter your " << i + 1 << "sexo: ";
cin >> sexo[i];
if (strcmp(sexo[i], feminino)==0){ // problem in here
cout << "that's ok" << endl;
}
} while (nome[i] == "0");
}
return 0;
}
You've been reading "tutorials" for C, or "tutorials" for C++ that actually teach you a terrible and outdated mix of C and C++.
The function strcmp is from the C Standard Library, and does not operate on the C++ std::string type.
To compare two std::strings, simply write:
if (sexo[i] == feminino) {
I find it hard to believe that your C++ book does not teach you this.
These are a few correct ways to compare these strings (in reverse order of preference)
if (strcmp(sexo[i].c_str(), feminino.c_str()) == 0) {
if (sexo[i].compare(feminino)) == 0) {
if (sexo[i] == feminino) {
You are using the wrong compare function. What you are using works with char * (it is used in C) but here you have std::string so you have to use std::string::compare()
Change your code to this:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string sexo[20], feminino; // problem in here
feminino = "f";
for (int i = 0; i < 3; i++) {
do {
cout << endl << "enter your " << i + 1 << "sexo: ";
cin >> sexo[i];
if (sexo[i].compare(feminito) == 0){
cout << "that's ok" << endl;
}
} while (nome[i] == "0");
}
return 0;
Note that you can also use sexo[i] == feminito as you have relational operators for std::string (see here for examples)
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'.
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
I have a hangman program, but I'm having issues with randomly choosing a word out of the list...
I get the errors:
-error C2661: 'rand' : no overloaded function takes 1 arguments
-IntelliSense: too many arguments in function call
They are both referring to the rand function noted in the code where I'm trying to randomly choose a word out of the array so the user can guess.
// Hang.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
using namespace std;
const int MAXLENGTH=80;
const int MAX_TRIES=5;
const int MAXROW=7;
int letterFill (char, char[], char[]);
void initUnknown (char[], char[]);
int main ()
{
char unknown [MAXLENGTH];
char letter;
int num_of_wrong_guesses=0;
char word[MAXLENGTH];
char words[][MAXLENGTH] =
{
"india",
"america",
"germany",
"china",
"canada"
};
//THIS IS WHERE THE ISSUE IS OCCURRING vvvvvvv
//choose and copy a word from array of words randomly
rand();
int n=rand(5);
strcpy(word,words[n]);
// Initialize the secret word with the * character.
initUnknown(word, unknown);
// welcome the user
cout << "\n\nWelcome to Hangman!";
cout << "\n\nYou have " << MAX_TRIES << " tries to try and guess the word.";
cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
// Loop until the guesses are used up
while (num_of_wrong_guesses < MAX_TRIES)
{
cout << "\n\n" << unknown;
cout << "\n\nGuess a letter: ";
cin >> letter;
// Fill secret word with letter if the guess is correct,
// otherwise increment the number of wrong guesses.
if (letterFill(letter, word, unknown)==0)
{
cout << endl << "Sorry, that letter was wrong." << endl;
num_of_wrong_guesses++;
}
else
{
cout << endl << "You found a letter!" << endl;
}
// Tell user how many guesses has left.
cout << "You have " << MAX_TRIES - num_of_wrong_guesses;
cout << " guesses left." << endl;
// Check if they guessed the word.
if (strcmp(word, unknown) == 0)
{
cout << word << endl;
cout << "You guessed it!";
break;
}
}
if(num_of_wrong_guesses == MAX_TRIES)
{
cout << "\nSorry, you lose...you've been hanged." << endl;
cout << "The word was : " << word << endl;
}
getch();
return 0;
}
/* Take a one character guess and the secret word, and fill in the
unfinished guessword. Returns number of characters matched.
Also, returns zero if the character is already guessed. */
int letterFill (char guess, char secretword[], char guessword[])
{
int i;
int matches=0;
for (i = 0; secretword[i]!='\0'; i++)
{
// Did we already match this letter in a previous guess?
if (guess == guessword[i])
return 0;
// Is the guess in the secret word?
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
// Initialize the unknown word
void initUnknown (char word[], char unknown[])
{
int i;
int length = strlen(word);
for (i = 0; i < length; i++)
unknown[i]='*';
unknown[i]='\0';
}
// end
rand takes no argument
You probably want :
int n=rand() % 5;
std::rand() generates a pseudo random number, if you want a number 0, 1, 2 3 or 4, which i guess you are trying to do use the following:
int n = rand()%5;
This generates a random number and then the % gives the rest value if you would divide by 5. If the random number is 12, you can 'put two fives in it', and the rest value will be 2.
One thing to note is that in C++ using rand() is generally a bad idea, because it will not give you a truly random number, and using % makes it worse, but I think you will be fine since this is just a small program.
Watch this talk if you want to know how to properly generate a random number in c++