There is a problem with strstr function. I have tried to compile password program, but it falls. Any help would be highly appreciated
#include <stdio.h>
#include <string.h>
using namespace std;
int main(){
char s[5], password[]="kuku";
int i,k=0;
for (i=0; !k && i<3;i++){
printf("\ enter password: \n");
gets(s);
if (strstr(s.password[])) k=1;
}
if(k) printf("password accepted");
else printf("password not accepted");
return 0;
}
if (strstr(s.password[])) k=1;
What did you want to accomplish with this? strstr() needs two arguments (haystack and needle, meaning that you want to find the needle in the haystack). You only pass one argument, which is wrong.
The correct code will be something like:
if (strstr(s, password) != NULL) k=1;
In this expression
strstr(s.password[])
there are two errors. The first one is that the separator of arguments is comma while you are using a dot.
The second one is that instead of the construction password[] you have to use the expression password
Take into account that the function strstr is not suitable to check whether two strings are equal each other. It is better to use function strcmp.
And the function gets is not supported by the C standard. Use instead function fgets.
And as you are trying to compile the program as a C++ program then use the standard class std::string instead of raw character arrays.
Related
Hi i'm having trouble making a function that checks the data type of a variable and checks it to make sure if a data type is similar to it in C++. Here's my code so far:
#include <iostream>
#include <typeinfo>
using namespace std;
int main() {
int typeCheck(string words, string typeWanted);
//make number assurance function .
string word;
cin >> word;
typeCheck(word, "string");
}
int typeCheck(string words, string typeWanted) {
if (typeid(words).name() != typeid(typeWanted).name()) {
cin.clear();
cin.ignore();
return 0;
}
else if (typeid(words).name()== typeid(typeWanted).name())
cout << "All good";
}
When I run the code it keeps saying the same output which is: All good even if I put a string or an int when its not the correct one. Instead of saying this I want it to clear the buffer and ignore it. Can anyone help me with this problem? Thanks in advance!
C++ is a statically typed language, meaning that the type is known at compile time. It will never be known only at run time.
What that means is that in your example:
int typeCheck(string words, string typeWanted);
both words and typeWanted will always be strings. If it is ever not a string, it will fail to compile. Thus, using typeid() in this situation is somewhat pointless. Your if statement will always be false, and your else-if statement will always be true.
Instead, you would want to use typeid() when you don't know they will be the same type, like in some sort of template situation:
template <class WordsType, class TypeWantedType>
int typeCheck(WordsType words, TypeWantedType typeWanted);
Here, a typeid() comparison makes more sense, because you don't really know if words and typeWanted are both strings.
You could do something like this instead:
template <class WordsType>
int typeCheck(WordsType words, string typeWanted) {
if (typeid(words).name() != typeWanted) {
//...
}
// ...
}
This would compare an unknown type to a wanted type.
Finally, there is another option, #RSahu's option from the comments:
if(words == typeWanted) {
//...
}
This will compare the input the user gave to the string "string".
It's unclear to me what you want to do exactly, so I can't recommend which one you should use, but at least now you have a couple of options.
It is because you are converting the type to string eaither way so it will allways trigger as correct as long as it is a string in the function input.
I would recommend that you use a template type so that whatever you enter into the TypeCheck() function will retain its type.
Screenshot 1
Here's my code.
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
class Dragon
{
public:
char element[30];
int energy;
};
int main()
{
Dragon dragon;
char name[30];
cout<<"Enter element.\n\n";
cin>>name;
if(name=='Hell')
{
strcpy(dragon.element,"Hell Dragon");
dragon.energy=15000000;
}
else if(name=='Dark')
{
strcpy(dragon.element,"Dark Dragon");
dragon.energy=1000000;
}
else
cout<<"Unknown Dragon.";
cout<<"\nDragon's element = "<<dragon.element<<"\nDragon's energy level = "<<dragon.energy;
getch();
return 0;
}
Just tried this program on my own in C++ and have problems in fixing the following errors-
Errors and Warnings
If you do have an idea on how I can modify this, please help me out.
Thank you.
One cause of your issues is that == can't be used to compare contents of character arrays.
Solution 1: Use std::string
The std::string data type is the preferred data structure in C++ for text strings.
The std::string has overloaded == for comparing strings.
The std::string also has a find method for searching for a substring.
Solution 2: Use strcmp
The C language uses character arrays for strings. The C language also has str*() functions for processing character arrays.
The C++ language uses the str*() functions for processing the C-Style strings (character arrays).
Use strcmp to compare character arrays with string literals:
if (strcmp(name, "Hell") == 0)
You may also want to use strstr for finding substrings or strchr for finding characters in a character array (C-style string).
I have a piece of code that asks for user input, it is type "string" and its a really simple process, i want whatever the user inputs to be converted using the tolower() function. It does exactly as its supposed to do, but i can't seem to assign it to the same variable. Any help please?
#include <locale>
#include <string>
#include <iostream>
//maybe some other headers, but headers aren't the problem, so I am not going to list them all
while (nCommand == 0)
{
locale loc;
string sCommand;
cin >> sCommand;
for (int i = 0; i < sCommand.length(); ++i)
{
sCommand = tolower(sCommand[i],loc);
cout << sCommand;
}
For example if the user types in Help sCommand would be h
How I want it to look like it that if the user types in HELP or Help or HeLp
sCommand should be 'help' either way
You're assigning a string to a character when really what you want to do is assign the character stored at the position to the lower case version.
Therefore change this:
sCommand = tolower(sCommand[i], loc);
to this:
sCommand[i] = tolower(sCommand[i], loc);
// ^^^
This is another case where Boost String Algorithms would reduce the whole problem to one single expression:
boost::algorithm::to_lower(sCommand)
Try the Boost libraries. It will help you immensely in the long run and let you concentrate on real problems rather than silliness like being the one-millionth programmer to write their own "convert string to lower-case" function.
So, I've been doing Reddit's daily programmer #140 and can't use std::toupper and std::erase.
Includes:
#include <iostream>
#include <string>
#include <cctype>
Part with toupper and erase (used to transform words to 'CamelCase'):
std::string tekst;
std::cin >> tekst;
tekst[0] = std::touppper(tekst[0]);
for(unsigned int i = 0; i < tekst.size(); i++){
if(tekst[i] == 32){
std::erase(tekst[i], 1);
tekst[i] = std::toupper(tekst[i]);
}
}
And compiler shows errors:
error: 'touppper' is not a member of 'std'
error: 'erase' is not a member of 'std'
What can cause it? Thanks in advance!
Not
std::touppper
but
std::toupper
You need to pass a locale to the function, see for example: http://www.cplusplus.com/reference/locale/toupper/
std::touppper does not exist, as it is spelled with two p's, not with three :). std::erase is not a standard function, check this: Help me understand std::erase
You probaly want to use std::toupper() as the basis of your implementation. Note, however, that std::toupper() takes its argument as int and requires that the argument is a positive value of EOF. Passing negative values to the one argument version of std::toupper() will result in undefined behavior. On platforms where char is signed you will easily get negative values, e.g., when using ISO-Latin-1 encoding with my second name. The canonical approach is to use std::toupper() with the char convert to an unsigned char:
tekstr[0] = std::toupper(static_cast<unsigned char>(tekstr[0]));
With respect to erase() you are probably looking for std::string::erase():
tekstr.erase(i);
Note that if the string ends in a space, you don't want to access the character at index i after blowing the last space away!
Let me make this clear right away, this is for a college class. I cannot use C++ libraries, only standard C libraries. Do not suggest that I use C++ strings or cin/cout because that will not help me for this assignment.
My issue: I have global character arrays in the main function. I need to pass strings to the global character arrays from scanf() in a function foo(). Everything compiles fine, the issue is, the scanf() function seems to have no affect on the global character arrays that it points to. I'm using the "address of" operator (&) as the reference books indicate to do. Perhaps, I'm not understanding the relationship between the character array pointer and the scanf() "address of" (&). I feel I've looked everywhere for a solution.
I've spent several hours on this issue so I'm now looking for expert advice.
Here is a simplified version of my program.
#include <stdio.h>
void foo(char arr1[], char arr2[]);
int main(void)
{
char arr1[20] = "initial";
char arr2[25] = "second";
foo(arr1); // <------- should change it to the string "second" upon scanf()
printf("Test Return Value: %s\n",arr1); // <---- returns "initial" (the problem)
printf("Enter a test value: ");
scanf("%s", &arr1);
printf("Test Return Value: %s\n",&arr1);
// ---------------------- this code is not part of the issue
fflush(stdin);
getchar();
return 0;
// ----------------------
}
void foo(char arr1[], char arr2[])
{
// there will be many returned values
printf("Enter a test value: ");
scanf("%s", &arr1); // <---------- the problem function (input < 20 chars)
}
scanf("%s", &arr); // <---------- the problem function (input < 20 chars)
should be
scanf("%s", arr); // <---------- the problem function (input < 20 chars)
The perils of using the C io functions!
Although you have updated saying solved I have a few observation which you might want to consider:
1. Get rid of & before arr1 in scanf & printf calls (which has solved your problem as mentioned by Ayjay & Dennis)
2. Correct number of parameters not passed to function foo (as mentioned by Adrian Cornish). Thus code will not compile.
3. fflush(stdin); is undefined behavior. fflush is only for output streams. Please don't use it with stdin. Refer this SO question for details.
4. If this is a C++ source please use #include <cstdio> instead of #include <stdio.h>
Always compile code with full compiler warnings and resolve all of them. It is a good practice. :)
Hope this helps!
The correct syntax for the scanf function is:
scanf("%s", arr);
You only need the & operator for simple variables, not for arrays / pointers.
Besides of that, you will have to correct the improper use of arr1, arr2 and arr. Parts of your code make use of the first two arrays, others of the latter.