i want the user to input a passwort. of course it's a secret passwort so nobody should see it.
so i tried to replace the letters and numbers the user inputs, with ' * '. here is my try.
while ((pw=getch())!='x'){
cout << "*";
strcpy(pwstring,pw);
}
input_pw=atoi(pwstring.c_str());
later i want the 'x' to be a 'enter'. but at the moment it's not important. with this, i get some compiler errors under Visual Studio.
Fehler 3
error C2664: 'strcpy': Konvertierung des Parameters 1 von 'char' in 'char *' nicht möglich c:\users\tim\desktop\kalssnne\methoden.h zeile: 70
i will try to translate this.
error 3
error C2664: 'strcpy': converting of parameter 1 from 'char' to 'char*' is not possible.
official english error code
"'function' : cannot convert parameter number from 'type1' to 'type2'"
thank u: R. Martinho Fernandes
but what does this mean, and how can i fix it?
hope u can help me
greetings.
Your question isn't as much about C++ as it is about how to interact with your terminal. The language is (deliberately) entirely agnostic of how input and output are handled, and everything that you're worried about is how the terminal behaves. As such, any answer will depend heavily on your platform and your terminal.
In Linux, you will probably want to look into termios.h or ncurses.h. There's an old Posix function getpass() which does something similar to what you want, but it's deprecated.
Unfortunately I have no idea how to approach terminal programming in Windows.
On a posix system use getpass (3).
It won't give you asterix echos, instead it echos nothing, but it is the way to do it.
Or if you are on a BSD system you could use readpassphrase (3) which is more flexible than the older call.
as R. Martinho Fernandes says: strcpy doesn't do what you think it does.
strcpy takes a char* buffer, and a char* source, and copies all of the data from the second (up to the first zero character) to the first. The easiest solution is to keep track of the length of pwstring and add characters one at a time:
char pwstring[100];
int length = 0;
while ((pw=getch())!='x' && length < 99){
cout << "*";
pwstring[length] = pw;
length = length + 1;
}
pwstring[length] = '\0';
int pwint = atoi(pwstring);
[EDIT] If pwstring is a std::string, then this becomes REALLY easy, since it already keeps track of it's own length.
std::string pwstring;
while ((pw=getch())!='x'){
cout << "*";
pwstring += pw;
}
int pwint = atoi(pwstring.c_str());
strcpy(pwstring,pw);
I'm guessing that pwstring is a std::string? strcpy is a c function, it acts on 'c' null terminated strings. You are providing it with a c++ string and an int.
Related
error: incompatible types in assignment of 'std::__cxx11::string' {aka'std::__cxx11::basic_string<char>'} to 'char [100]'
error: cannot convert 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} to 'const char*'
and I got the above two errors for these lines of codes
string s1=asctime(localtime(&timetoday));;
string r=s1.substr(4,6);
ch=r; //char ch[100];(defined aleady)
//1st error was in line just above this comment
if(strcmp(r,"Dec 20")==0)
//2nd error was in line just above this comment
{
cout<<"made my first try for creating this program";
}
else if(strcmp(r,"Dec 21")==0)
{
cout<<"Shortest day of the year";
}
I'm trying to create a simple remainder program in C++ using code blocks.
The problem is in the following line:
ch = r;
The variable ch is of type char[100], the variable r is of type std::string. These types are not compatible, you cannot assign an std::string to a char array.
You probably want to write the following instead:
strcpy( ch, r.c_str() );
However, it would be simpler not to use C-style strings at all, and instead use std::string everywhere, like this:
string s1=asctime(localtime(&timetoday));;
string r=s1.substr(4,6);
if( r == "Dec 20" )
{
cout<<"made my first try for creating this program";
}
else if( r == "Dec 21" )
{
cout<<"Shortest day of the year";
}
Another mistake in your program seems to be that you are calling strcmp twice, once like this:
strcmp(r,"Dec 20")
And once like this:
strcmp(ch,"Dec 21")
The second one is correct, but the first one is wrong, as you must pass a C-style string (a char array), and not a C++ style string (a std::string). You probably meant to write ch instead of r. Alternatively, if you want to keep using r, you can write r.c_str() instead, which will return a C-style string. But, as already stated above, the best solution would probably be to use std::string everywhere and not use strcmp at all, as it is only intended for C-style strings.
The code is incomplete, i.e. ch is not defined, but you probably want to use r.c_str() in the first call to strcmp, and in the 2nd case r.c_str() instead of ch.
strcmp compares two cstrings(const char*), you are passing a std::string. try something like ``if(r == "Dec 20") ...```
ch = r you are mixing string with char array or c with cpp . Why not make your life easy you can use std::copy in this way
std::copy(r.begin(),r.end(),ch);
Happy Coding.
The variable ch is of kind char[100], the variable r is of kind std::string. These sorts are not compatible, you can not assign an std::string to a char array
I was seeing an old simple algorithm I had done a while ago. I did it using dev-c ++, but now I compiled it in visual studio and it doesn't work. Visual studio compiler says: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. (line 17)
In this easy project you will type a phrase, then you get the phrase translated in hex (each character).
So why dev-c++ doesn't tell me that? Did I make any mistakes? Or not... The code is ok? I want to understand that because it's not the first time i receive that error.
Code execution example:
Please insert a phrase: hello world!
The string -hello world!- converted in hex is
68 65 6c 6c 6f
20 77 6f 72 6c
64 21
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string phrase;
char* chArray;
cout << "Pls insert a phrase:\t";
getline(cin, phrase);
chArray = new char[phrase.size() + 1];
strcpy(chArray, phrase.c_str()); //THE ERROR IS HERE!
cout << "The string -" << phrase << "- converted in hex is\n";
for (int i = 1; i < static_cast<int>(phrase.size() + 1); i++)
{
int ch = (int)chArray[i-1];
cout << setbase(16) << ch << " ";
if (i % 5 == 0)
cout << "\n";
}
return 0;
}
You get this warning when you use any of the "unsafe" byte copying functions. It's mostly specific to MSVC.
To fix it, use strcpy_s which requires you to also pass a maximum number of bytes to copy (which should be the size of the destination buffer). This prevents buffer overflows.
strcpy_s(chArray, phrase.size()+1, phrase.c_str());
That said, it's easier to use std::string for all this in C++
Visual studio compiler says: 'strcpy': This function or variable may be unsafe.
This is because you've used strcpy, and your compiler considers it a potentially unsafe function. The purpose of the warning is to inform you of this perceived lack of safety. The message advises you how to disable the warning in case you wish to keep using the function.
The typical, safer alternative is to use std::string instead. In case of your particular program, the use of strcpy seems completely redundant. Instead of chArray[i-1], you could use phrase[i-1].
So why dev-c++ doesn't tell me that?
Diagnostic messages are up to discretion of the implementation. You're using another compiler with this IDE, and that one does not warn you for using strcpy.
Did I make any mistakes?
Someone might argue that the choice to use strcpy is a mistake. But it's a mistake because it is easy to misuse by accident. As far as I can tell, you've used it correctly.
That said, part of the unsafety is that incorrect use is not necessarily easy to recognise. If it was easy, then the compiler would tell you when you use it incorrectly. But it's not easy, and the compiler cannot do that in general.
Besides the use of strcpy, there is another potential issue: You leak the memory that you allocate for the character array.
Firstly, I know my title looks like a commonly asked question, but hear me out. When I say 'Parsing arguments' I don't mean the command line arguments that get passed to the program when it starts up. I'm trying to create a seperate system to receive commands and parse them in runtime.
Main:
int main(int argc, char *args[])
{
cout << "Started up." << endl;
reloop();
}
// Main execution point. Prints text to the console and moves to a void:
void reloop()
{
char *str;
cin >> str;
parseargs(str);
}
// Starts waiting for inputted data, if found, move onto parseargs void.
void parseargs(char *args)
{
char *strings[10];
char delim[] = " ";
int i = 0;
strings[i] = strtok(args,delim);
if(strings[0] == "try")
{
cout << "WORKED!" << endl;
reloop();
}
else
{
cout << "Na. Didn't work." << endl;
reloop();
}
}
// Takes the arguments passed to it, splits them via a space and passes them to an array. From here, compares the first entry in the array to a command. If they equal, output success note.
Now, I'm a C# programmer for quite some time and have only just started C++.. What am I doing wrong? When the program starts up, an error comes up with:
Debug Assertion Failed!
Program: C:\Windows\system32\MSVCP110D.dll
File: c:\program files\microsoft visual studio 11.0\vc\include\istream
Line: 990
Expression: Invalid null pointer
*Note: I do have declarations for each function at the top of the CPP file.
One bug I can find in your code is in function void reloop()
char *str;
cin >> str; <---"Undefined behavior"
You don't allocate memory for str.
correct it either:
char str[SIZE];
Dynamically allocate space: char* str = new char[SIZE];
Next error is:
if(strings[0] == "try")
should be:
if(strcmp( strings[0], "try")!=0)
void reloop() {
char *str; /* WRONG */
cin >> str;
parseargs(str);
}
You should have written it that way :
void reloop() {
char str[BUF_MAX]; /* ok but take care of buffer overflow; maybe use std::string */
cin >> str;
parseargs(str);
}
Even if you know C# please note that you don't know anything about C++ and that even if you're very smart intuition will guide you down the wrong path (actually especially if you're very smart: C++ in quite a few parts is indeed "illogical" so a logic mind is not going to help at all).
The reason is that C++ is the way it is for a mix of complex reasons, including committee effect and a lot of historical heritage. No matter how smart you are you're not going to guess neither history nor what a committee decided.
How char * are part of C++ is one of these things that can only be understood if you know history (especially history of C). The error in you program is that you cannot write
char *str;
cin >> str;
because you didn't allocate the memory for it. It would also be bad code because potentially overflows the memory you allocate. If you're missing this then you're going to miss a LOT of other much more subtle points of C++ programming.
Do yourself a favor and start by reading cover-to-cover a good C++ book instead of just experimenting with a compiler.
Experimenting is not a reasonable path with C++ because of its very complex and sometimes illogical structure and because of "undefined behaviour" that means that when doing a mistake you cannot count on a clear error message but can get crazy behaviour instead (including the most dangerous crazy behaviour... i.e. the code apparently will work anyway even when a mistake is present).
Your code problem has been explained by others.
There is one more general problem with your code: you are not using existing functions or libraries which would do what you need.
Pure C solution:
http://www.gnu.org/software/libc/manual/html_node/Getopt.html
C++ Boost program options:
http://www.boost.org/doc/libs/1_54_0/doc/html/program_options.html
I'm trying to write a code in C++ that allows you to enter some text and it will open a website with the variable s_input appended to it. However, I get this error:
'system' : cannot convert parameter 1 from 'std::string' to 'const
char *'
I get that error for the last line you see.
cin >> s_input;
transform(s_input.begin(), s_input.end(), s_input.begin(), tolower);
s_input = "start http://website.com/" + s_input + "/0/7/0";
system(s_input);
I am new to C++ and this is more of a learning program.. So please show as many examples as possible! Thanks!
If s_input is a std::string (I'm betting it is):
system(s_input.c_str());
The function system takes a const char* as parameter, as the error message clearly states.
I am getting a crash while executing the following code ocassionally at sprintf_s. This code was working many years without any problems. When I gave the size in strcat_s and sprintf_s as in the statements below, the crash is not appearing. What could be the reason for this?
strcat_s(sztmpCurrDate,100,sztmpCurrTime);
sprintf_s(sztmpCurrDate,100,"%s:%0.3d",sztmpCurrDate,curTime.wMilliseconds););
char sztmpCurrDate[100] = "";
char sztmpCurrTime[100] = "";
SYSTEMTIME curTime;
GetLocalTime(&curTime);
GetLocalTime(&curTime);
GetDateFormat(LOCALE_USER_DEFAULT,
DATE_SHORTDATE,
&curTime,
NULL,
sztmpCurrDate,
100);
GetTimeFormat(LOCALE_USER_DEFAULT,
TIME_FORCE24HOURFORMAT,
&curTime,
"HH':'mm':'ss",
sztmpCurrTime,
100);
strcat_s(sztmpCurrDate," ");
strcat_s(sztmpCurrDate,sztmpCurrTime);
sprintf_s(sztmpCurrDate,"%s:%0.3d",sztmpCurrDate,curTime.wMilliseconds);
From the documentation for sprintf_s:
If copying occurs between strings that overlap, the behavior is undefined.
Your code:
sprintf_s(sztmpCurrDate,"%s:%0.3d",sztmpCurrDate,curTime.wMilliseconds);
copies from the source to the destination sztmpCurrDate. Also, you haven't specified the size of the destination string, which is required by sprintf_s (I don't know how your code even compiled like that). Try:
sprintf_s(sztmpCurrDate + strlen(sztmpCurrDate), 100-strlen(sztmpCurrDate),
":%0.3d",curTime.wMilliseconds);
A better approach, since you're using C++, is to use std::string and then you won't have to worry about this sort of C string manipulation error.
Wrong syntax!!!
Second argument of sprintf_s is length of your buffer and in your case when program crashes you provided pointer to C string (char *). This is absolutely syntax error.
The compiler probably issued a warning, but sadly has let this pass. This is because sprintf_s takes three arguments + variable number of arguments. In your wrong case you provided three arguments so the compiler was satisfied, but he treated your "format string" as "number of arguments" and sztmpCurrDate as "format string".
If you used any other function with fixed number of arguments and you provided less than needed this would be a compile error.
You are probably using the incorrect version:
sprintf_s(sztmpCurrDate,"%s:%0.3d",sztmpCurrDate,curTime.wMilliseconds);
Instead it should be:
int slen = strlen(sztmpCurrDate) + 1;
sprintf_s(sztmpCurrDate, slen, "%s:%0.3d",sztmpCurrDate,curTime.wMilliseconds);
Refer to this sprintf_s for more information.
The code worked correctly, the code is not correct.
sprintf(sztmpCurrDate,"%s:%0.3d",sztmpCurrDate,curTime.wMilliseconds);
Rewrite as
sprintf(&sztmpCurrDate[strlen(sztmpCurrDate)],"%0.3d",curTime.wMilliseconds);
And for home work tell us why .....