C++ strcpy_s IntelliSense error - c++

I have error in this place:
strcpy_s(msgToGraphics, game.board_now());
the error is:
IntelliSense: no instance of overloaded function "strcpy_s" matches the argument list argument types are: (char [1024], std::string)
and here is the game.board_now func:
string Board::board_now()
{
return _board;
}
and here is the rest of the code where I try to use the strncpy_s():
#include "Pipe.h"
#include "Board.h"
#include <iostream>
#include <thread>
using namespace std;
void main()
{
srand(time_t(NULL));
Pipe p;
bool isConnect = p.connect();
string ans;
while (!isConnect) {
cout << "cant connect to graphics" << endl;
cout << "Do you try to connect again or exit? (0-try again, 1-exit)" << endl;
cin >> ans;
if (ans == "0") {
cout << "trying connect again.." << endl;
Sleep(5000);
isConnect = p.connect();
}
else {
p.close();
return;
}
}
char msgToGraphics[1024];
// msgToGraphics should contain the board string accord the protocol
// YOUR CODE
Board game;
//strcpy_s(msgToGraphics, game.board_now()); // just example...
p.sendMessageToGraphics("rnbkqbnrpppppppp################################PPPPPPPPRBNKQNBR0"); // send the board string
// get message from graphics
string msgFromGraphics = p.getMessageFromGraphics();
while (msgFromGraphics != "quit") {
game.change_board(msgFromGraphics);
game.change_board_sq(msgFromGraphics);
strcpy_s(msgToGraphics, game.board_now()); // msgToGraphics should contain the result of the operation
// return result to graphics
p.sendMessageToGraphics(msgToGraphics);
// get message from graphics
msgFromGraphics = p.getMessageFromGraphics();
}
p.close();
}
The code is basically for a chess program and I try to recieve the chess board after the changes I made and I dont know how to format him in the strcpy_s() in order to put him in the array and send it back to the given exe.

Since C11 strcpy_s is
1) `char *strcpy( char *dest, const char *src );`
2) errno_t strcpy_s(char *restrict dest, rsize_t destsz, const char *restrict src);
strcpy_s is Same as (1),
except that it may clobber the rest of the destination array with unspecified values and that the following errors are detected at runtime and call the currently installed constraint handler function:
src or dest is a null pointer
destsz is zero or greater than RSIZE_MAX
destsz is less or equal strnlen_s(src, destsz); in other words, truncation would occur
overlap would occur between the source and the destination strings
The behavior is undefined if the size of the character array pointed to by dest <= strnlen_s(src, destsz) < destsz; in other words, an erroneous value of destsz does not expose the impending buffer overflow.
As all bounds-checked functions, strcpy_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined by the implementation and if the user defines __STDC_WANT_LIB_EXT1__ to the integer constant 1 before including string.h.
Refer the page for more information http://en.cppreference.com/w/c/string/byte/strcpy

The simplest solution would be to make msgToGraphics a std::string too, and then instead of using the C function strcpy_s, just assign to it to do the same thing:
msgToGraphics = game.board_now();
If you need to get a non-const char* to the underlying array, you can do it like this (with the usual caveats):
p.sendMessageToGraphics(&msgToGraphics[0]);
But really you should change the interface to not rely on a char array being passed in. (Hint: use std::string instead.)

Related

How do I search in the struct in c++ [duplicate]

I'm trying to compare a character array against a string like so:
const char *var1 = " ";
var1 = getenv("myEnvVar");
if(var1 == "dev")
{
// do stuff
}
This if statement never validates as true... when I output var1 it is "dev", I was thinking maybe it has something to do with a null terminated string, but the strlen of "dev" and var1 are equal... I also thought maybe var1 == "dev" was comparing "dev" against the memory location of var1 instead of the value. *var1 == "dev" results in an error.... tried many things, probably a simple solution for the saavy c++ developer (I havent coded c++ in a looong time).
edit:
we've tried
if(strcmp(var1, "dev") == 0)
and
if(strncmp(var1, "dev", 3) == 0)
Thanks
edit: After testing at home I'm just going to suggest my co-worker changes the datatype to a string. I believe he was comparing a char array of a large size against a string. I put together a program that outputs sizeof, strlen, etc to help us work through it. Thanks to everyone for the help.
Use strcmp() to compare the contents of strings:
if (strcmp(var1, "dev") == 0) {
}
Explanation: in C, a string is a pointer to a memory location which contains bytes. Comparing a char* to a char* using the equality operator won't work as expected, because you are comparing the memory locations of the strings rather than their byte contents. A function such as strcmp() will iterate through both strings, checking their bytes to see if they are equal. strcmp() will return 0 if they are equal, and a non-zero value if they differ. For more details, see the manpage.
You're not working with strings. You're working with pointers.
var1 is a char pointer (const char*). It is not a string. If it is null-terminated, then certain C functions will treat it as a string, but it is fundamentally just a pointer.
So when you compare it to a char array, the array decays to a pointer as well, and the compiler then tries to find an operator == (const char*, const char*).
Such an operator does exist. It takes two pointers and returns true if they point to the same address. So the compiler invokes that, and your code breaks.
IF you want to do string comparisons, you have to tell the compiler that you want to deal with strings, not pointers.
The C way of doing this is to use the strcmp function:
strcmp(var1, "dev");
This will return zero if the two strings are equal. (It will return a value greater than zero if the left-hand side is lexicographically greater than the right hand side, and a value less than zero otherwise.)
So to compare for equality you need to do one of these:
if (!strcmp(var1, "dev")){...}
if (strcmp(var1, "dev") == 0) {...}
However, C++ has a very useful string class. If we use that your code becomes a fair bit simpler. Of course we could create strings from both arguments, but we only need to do it with one of them:
std::string var1 = getenv("myEnvVar");
if(var1 == "dev")
{
// do stuff
}
Now the compiler encounters a comparison between string and char pointer. It can handle that, because a char pointer can be implicitly converted to a string, yielding a string/string comparison. And those behave exactly as you'd expect.
In this code you are not comparing string values, you are comparing pointer values. If you want to compare string values you need to use a string comparison function such as strcmp.
if ( 0 == strcmp(var1, "dev")) {
..
}
"dev" is not a string it is a const char * like var1. Thus you are indeed comparing the memory adresses. Being that var1 is a char pointer, *var1 is a single char (the first character of the pointed to character sequence to be precise). You can't compare a char against a char pointer, which is why that did not work.
Being that this is tagged as c++, it would be sensible to use std::string instead of char pointers, which would make == work as expected. (You would just need to do const std::string var1 instead of const char *var1.
There is more stable function, also gets rid of string folding.
// Add to C++ source
bool string_equal (const char* arg0, const char* arg1)
{
/*
* This function wraps string comparison with string pointers
* (and also works around 'string folding', as I said).
* Converts pointers to std::string
* for make use of string equality operator (==).
* Parameters use 'const' for prevent possible object corruption.
*/
std::string var0 = (std::string) arg0;
std::string var1 = (std::string) arg1;
if (var0 == var1)
{
return true;
}
else
{
return false;
}
}
And add declaration to header
// Parameters use 'const' for prevent possible object corruption.
bool string_equal (const char* arg0, const char* arg1);
For usage, just place an 'string_equal' call as condition of if (or ternary) statement/block.
if (string_equal (var1, "dev"))
{
// It is equal, do what needed here.
}
else
{
// It is not equal, do what needed here (optional).
}
Source: sinatramultimedia/fl32 codec (it's written by myself)
your thinking about this program below
#include <stdio.h>
#include <string.h>
int main ()
{
char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
int n;
puts ("Looking for R2 astromech droids...");
for (n=0 ; n<3 ; n++)
if (strncmp (str[n],"R2xx",2) == 0)
{
printf ("found %s\n",str[n]);
}
return 0;
}
//outputs:
//
//Looking for R2 astromech droids...
//found R2D2
//found R2A6
when you should be thinking about inputting something into an array & then use strcmp functions like the program above ... check out a modified program below
#include <iostream>
#include<cctype>
#include <string.h>
#include <string>
using namespace std;
int main()
{
int Students=2;
int Projects=3, Avg2=0, Sum2=0, SumT2=0, AvgT2=0, i=0, j=0;
int Grades[Students][Projects];
for(int j=0; j<=Projects-1; j++){
for(int i=0; i<=Students; i++) {
cout <<"Please give grade of student "<< j <<"in project "<< i << ":";
cin >> Grades[j][i];
}
Sum2 = Sum2 + Grades[i][j];
Avg2 = Sum2/Students;
}
SumT2 = SumT2 + Avg2;
AvgT2 = SumT2/Projects;
cout << "avg is : " << AvgT2 << " and sum : " << SumT2 << ":";
return 0;
}
change to string except it only reads 1 input and throws the rest out
maybe need two for loops and two pointers
#include <cstring>
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
char name[100];
//string userInput[26];
int i=0, n=0, m=0;
cout<<"your name? ";
cin>>name;
cout<<"Hello "<<name<< endl;
char *ptr=name;
for (i = 0; i < 20; i++)
{
cout<<i<<" "<<ptr[i]<<" "<<(int)ptr[i]<<endl;
}
int length = 0;
while(name[length] != '\0')
{
length++;
}
for(n=0; n<4; n++)
{
if (strncmp(ptr, "snit", 4) == 0)
{
cout << "you found the snitch " << ptr[i];
}
}
cout<<name <<"is"<<length<<"chars long";
}

C++ will ignore if statement while using system() and while [duplicate]

I'm trying to compare a character array against a string like so:
const char *var1 = " ";
var1 = getenv("myEnvVar");
if(var1 == "dev")
{
// do stuff
}
This if statement never validates as true... when I output var1 it is "dev", I was thinking maybe it has something to do with a null terminated string, but the strlen of "dev" and var1 are equal... I also thought maybe var1 == "dev" was comparing "dev" against the memory location of var1 instead of the value. *var1 == "dev" results in an error.... tried many things, probably a simple solution for the saavy c++ developer (I havent coded c++ in a looong time).
edit:
we've tried
if(strcmp(var1, "dev") == 0)
and
if(strncmp(var1, "dev", 3) == 0)
Thanks
edit: After testing at home I'm just going to suggest my co-worker changes the datatype to a string. I believe he was comparing a char array of a large size against a string. I put together a program that outputs sizeof, strlen, etc to help us work through it. Thanks to everyone for the help.
Use strcmp() to compare the contents of strings:
if (strcmp(var1, "dev") == 0) {
}
Explanation: in C, a string is a pointer to a memory location which contains bytes. Comparing a char* to a char* using the equality operator won't work as expected, because you are comparing the memory locations of the strings rather than their byte contents. A function such as strcmp() will iterate through both strings, checking their bytes to see if they are equal. strcmp() will return 0 if they are equal, and a non-zero value if they differ. For more details, see the manpage.
You're not working with strings. You're working with pointers.
var1 is a char pointer (const char*). It is not a string. If it is null-terminated, then certain C functions will treat it as a string, but it is fundamentally just a pointer.
So when you compare it to a char array, the array decays to a pointer as well, and the compiler then tries to find an operator == (const char*, const char*).
Such an operator does exist. It takes two pointers and returns true if they point to the same address. So the compiler invokes that, and your code breaks.
IF you want to do string comparisons, you have to tell the compiler that you want to deal with strings, not pointers.
The C way of doing this is to use the strcmp function:
strcmp(var1, "dev");
This will return zero if the two strings are equal. (It will return a value greater than zero if the left-hand side is lexicographically greater than the right hand side, and a value less than zero otherwise.)
So to compare for equality you need to do one of these:
if (!strcmp(var1, "dev")){...}
if (strcmp(var1, "dev") == 0) {...}
However, C++ has a very useful string class. If we use that your code becomes a fair bit simpler. Of course we could create strings from both arguments, but we only need to do it with one of them:
std::string var1 = getenv("myEnvVar");
if(var1 == "dev")
{
// do stuff
}
Now the compiler encounters a comparison between string and char pointer. It can handle that, because a char pointer can be implicitly converted to a string, yielding a string/string comparison. And those behave exactly as you'd expect.
In this code you are not comparing string values, you are comparing pointer values. If you want to compare string values you need to use a string comparison function such as strcmp.
if ( 0 == strcmp(var1, "dev")) {
..
}
"dev" is not a string it is a const char * like var1. Thus you are indeed comparing the memory adresses. Being that var1 is a char pointer, *var1 is a single char (the first character of the pointed to character sequence to be precise). You can't compare a char against a char pointer, which is why that did not work.
Being that this is tagged as c++, it would be sensible to use std::string instead of char pointers, which would make == work as expected. (You would just need to do const std::string var1 instead of const char *var1.
There is more stable function, also gets rid of string folding.
// Add to C++ source
bool string_equal (const char* arg0, const char* arg1)
{
/*
* This function wraps string comparison with string pointers
* (and also works around 'string folding', as I said).
* Converts pointers to std::string
* for make use of string equality operator (==).
* Parameters use 'const' for prevent possible object corruption.
*/
std::string var0 = (std::string) arg0;
std::string var1 = (std::string) arg1;
if (var0 == var1)
{
return true;
}
else
{
return false;
}
}
And add declaration to header
// Parameters use 'const' for prevent possible object corruption.
bool string_equal (const char* arg0, const char* arg1);
For usage, just place an 'string_equal' call as condition of if (or ternary) statement/block.
if (string_equal (var1, "dev"))
{
// It is equal, do what needed here.
}
else
{
// It is not equal, do what needed here (optional).
}
Source: sinatramultimedia/fl32 codec (it's written by myself)
your thinking about this program below
#include <stdio.h>
#include <string.h>
int main ()
{
char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
int n;
puts ("Looking for R2 astromech droids...");
for (n=0 ; n<3 ; n++)
if (strncmp (str[n],"R2xx",2) == 0)
{
printf ("found %s\n",str[n]);
}
return 0;
}
//outputs:
//
//Looking for R2 astromech droids...
//found R2D2
//found R2A6
when you should be thinking about inputting something into an array & then use strcmp functions like the program above ... check out a modified program below
#include <iostream>
#include<cctype>
#include <string.h>
#include <string>
using namespace std;
int main()
{
int Students=2;
int Projects=3, Avg2=0, Sum2=0, SumT2=0, AvgT2=0, i=0, j=0;
int Grades[Students][Projects];
for(int j=0; j<=Projects-1; j++){
for(int i=0; i<=Students; i++) {
cout <<"Please give grade of student "<< j <<"in project "<< i << ":";
cin >> Grades[j][i];
}
Sum2 = Sum2 + Grades[i][j];
Avg2 = Sum2/Students;
}
SumT2 = SumT2 + Avg2;
AvgT2 = SumT2/Projects;
cout << "avg is : " << AvgT2 << " and sum : " << SumT2 << ":";
return 0;
}
change to string except it only reads 1 input and throws the rest out
maybe need two for loops and two pointers
#include <cstring>
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
char name[100];
//string userInput[26];
int i=0, n=0, m=0;
cout<<"your name? ";
cin>>name;
cout<<"Hello "<<name<< endl;
char *ptr=name;
for (i = 0; i < 20; i++)
{
cout<<i<<" "<<ptr[i]<<" "<<(int)ptr[i]<<endl;
}
int length = 0;
while(name[length] != '\0')
{
length++;
}
for(n=0; n<4; n++)
{
if (strncmp(ptr, "snit", 4) == 0)
{
cout << "you found the snitch " << ptr[i];
}
}
cout<<name <<"is"<<length<<"chars long";
}

Is there a way I can use a function to return the memory location of an array element?

I just started learning about pointers so I'd thought I'd share what I'm trying to do. Of a character array (let's call it c and it's equal to "Hello"), I'm trying to return the memory location of a certain element. Say the memory of location of 'l'. Here's what I have so far:
#include <iostream>
using namespace std;
char* str_char(char* c_ptr, char c);
int main()
{
char *c = "Hello";
cout << str_char(c, 'l') << endl;
return 0;
}
char* str_char(char* c_ptr, char c)
{
for (int i = 0; i < sizeof(c_ptr); i++)
{
if (*(c_ptr + i) == c)
{
return (c_ptr + i);
break;
}
}
}
After I use the function, it outputs "llo".
You are on the right track. However, there are a few things that are not right.
Use of sizeof(c_ptr) is not right. It works for your case due to happy coincidence.
sizeof(c_ptr) is equal to sizeof(char*). It is not equal to the size of the array from the calling function.
There is a missing return statement at end of the function -- the case where c is not found in c_ptr.
There is no need of the break; after the return;.
Also, you can simplify the function a little bit.
Here's an updated version:
char* str_char(char* c_ptr, char c)
{
for (char* cp = c_ptr; *cp != '\0'; ++cp )
{
if (*cp == c)
{
return cp;
}
}
return nullptr;
}
The earlier answer has covered the bugs, so I'll just answer the actual question...
The function does return the location of an array element.
The << operator treats every char* as a pointer to a zero-terminated string, and outputting the result of str_char works exactly like outputting c; it prints every character after that location until it encounters a zero.
If you want to output the value of the location itself, you need to cast it to a different type:
cout << static_cast<void*>(str_char(c, 'l')) << endl;
as << has an overload for void* that outputs the address itself.
R Sahu gave you answer that is slightly modified version of your function . That is legal code, but that is basicly a C code, except use of nullptr. Returning nullptr is non-canon and if nupllptr will be returned, what << operator would do? That's undefined behavior.
it is often agreed pattern to leave iterator (pointer) pointing at end of line (at the terminating zero) to avoid crash you may cause by returning nullptr.
char* str_char(char* c_ptr, char c)
{
char* cp = c_ptr;
for (; *cp != '\0'; ++cp )
{
if (*cp == c)
{
return cp;
}
}
return cp;
// if cp was declared inside scope , we can't retirn it's value
}
Normally you do not need to write own string functions.. bth C library and C++ got them already covered. C++ got set of abstract algorithmic functions, in your case a strchr, find or find_if is prudent:
#include <algorithm>
#include <iostream>
using std::cout;
int main()
{
char *c = "Hello";
cout << std::strchr(c, 'l') << '\n';
// with pointer to null-terminated string, strlen searches
// for zero char and returns the count of characters before it
cout << std::find(c, c + strlen(c), 'l') << '\n';
// with declared array we can use std:begin and std::end
char carr[] = "Hello";
cout << std::find(std::begin(carr),std::end(carr) , 'l') << '\n';
// with pointer to null-terminated string a lambda expression
// can be used to stop at 0 as well as at first key
const char key = 'l';
cout << std::find_if(c, c + strlen(c),[=](const char& item)
{
return (item == key) || (item == '\0');
}) << '\n';
return 0;
}
An std::vector or ::array or other containers can be used with those templates as well.
The <algorithms> header would save tons of time you need to debug your custom-tailored functions for search, iteration, etc.
P.S. cout and cin deal with char and char* in special way.. char* is always pointer at string, char is always a character, not a number, so casts are required if you mean otherwise.

C++ pointer function causes empty parameter

I'm making a virtual machine in C++. I have loaded in the contents of a file as a string. I pass this string to a function of type int*, but the problem is the string variable containing the contents of the file seems to be empty because when I try to use cout << file << endl; I get nothing.
Here is the file in question:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
class reedoovm {
private:
string filedata;
string instruction;
string file;
int instr;
int instructionCount;
int instructionPointer;
public:
int load_program(string filename) {
ifstream rdfile(filename);
while(rdfile >> instruction) { /* Get each instruction */
filedata += instruction; /* Append the instruction to filedata */
filedata += ","; /* Append a comma to separate each instruction */
instructionCount++;
}
rdfile.close(); /* Close the file */
return instructionCount; /* Return the filedata */
}
int *instrToArr(string file) {
//file = "02,0022,00E1,0022,00,04,73";
cout << file << endl;
stringstream hextoint;
unsigned int value;
string s = file; /* store fconv in a variable "s" */
string delimiter = ","; /* The delimiter */
size_t pos = 0;
string token;
int i = 0;
int inst;
static int* instarray;
instarray = (int*) calloc(instructionCount,sizeof(int));
while ((pos = s.find(delimiter)) != string::npos) { /* Convert hex instructions to decimal */
token = s.substr(0, pos);
stringstream hextoint(token);
hextoint >> hex >> value;
if (i < instructionCount) {
instarray[i] = value;
cout << instarray[i] << endl;
i++;
}
s.erase(0, pos + delimiter.length());
}
return instarray;
}
int getNextIntruction(string s) {
int *instruction = instrToArr(s);
cout << *instruction << endl;
return 0;
}
void run_program(string s) {
int loop = 1;
while (loop) {
instr = getNextIntruction(s);
loop = 0;
}
}
void execute_program(string s) {
file = load_program(s);
int * arr = instrToArr(file);
//cout << arr << endl;
//run_program(s);
}
};
int main(int argc, char* argv[]) {
reedoovm rd;
rd.execute_program(argv[1]);
return 0;
}
The function causing the problem is int *instrToArr(string file) {. I don't know why all of a sudden the file variable is empty.
Your code has many issues, but the one that is bugging you is probably
file = loadProgram(s);
because loadProgram has been defined as returning an integer (the number of instructions) and not a string, but you're assigning it to a string.
For what I'd call a design bug of C++ assigning an integer to a string is a perfectly legal instruction and means that the string will have one character with the value of the integer.
Officially the reason for accepting assignment from an integers is that it was thought that it could be useful to write
str += chr; // Adds the char at the end
where str is a string and chr a char. By extension if += was legal then it was thought that also assignment should be legal too (a logical jump I don't agree with in this specific case).
chars however in C++ are numbers and integers (or even doubles) can be converted implicitly to a char without any warning or any error. So it's for example also legal:
std::string s;
s = 3.141592654;
Other issues I can see in your code are:
1. instructionCount is not initialized
In C++ you must always initialize native type members (e.g. integers, doubles) in class instances in the constructor. The default constructor won't do it for you. The result is that when allocating the class instance those members will have random values and you don't want that. Official explanation for this rule is that initializing members that won't be access may penalize performance, if the programmer wants to pay for initialization then it has to write the initialization.
2. instrToArr returns a pointer to a local static variable
That variable that is however allocated each time the function is called thus leaking memory at each call if the caller doesn't take care of deallocation.
Note that in C++ writing:
static int * instarray = (int *)calloc(...);
is not the same as writing:
static int * instarray;
instarray = (int *)calloc(...);
because in the first case the allocation is done only once (the first time the code reaches that instruction) while in the second case the allocation is done every time.
3. You are using calloc
Your code is allocation a variable-sized array using calloc and this, while not a bad idea in absolute, requires very careful handling to avoid leaks or other errors (for example memory allocated with calloc must be freed with free and not with delete[] but the compiler cannot help the programmer remembering what was allocated with one or with the other method (new[]).
MUCH better unless there are very specific reasons to play with naked pointers and implicit sizes is to use std::vector for variable-sized arrays.
4. You seem to want hex -> int conversion
... but your code does nothing to do it. Unfortunately input parsing is a sad story in C++ and I, as one, prefer to use old c <stdio.h> functions for input and especially for output (where formatting in C++ is just too painful).
5. your getNextInstruction always returns 0
Nothing remains of the processing of instrToArr and also the array returned is just dropped on the floor after sending the address on output.
This means just leaking memory at every iteration.
6. your run_program just loops once
... thus at least the naming is confusing (there are no real loops).
7. your program doesn't do any kind of checking in main
If someone calls the program passing no arguments (a quite common case) then something bad is going to happen.
I think in load_program() instead of:
return instructionCount;
you meant:
return filedata;
And change the return type of load_program() to string
I suppose you have a typo
int * arr = instrToArr(file)
instead of
int * arr = instrToArr(filedata)

C++ Compare char array with string

I'm trying to compare a character array against a string like so:
const char *var1 = " ";
var1 = getenv("myEnvVar");
if(var1 == "dev")
{
// do stuff
}
This if statement never validates as true... when I output var1 it is "dev", I was thinking maybe it has something to do with a null terminated string, but the strlen of "dev" and var1 are equal... I also thought maybe var1 == "dev" was comparing "dev" against the memory location of var1 instead of the value. *var1 == "dev" results in an error.... tried many things, probably a simple solution for the saavy c++ developer (I havent coded c++ in a looong time).
edit:
we've tried
if(strcmp(var1, "dev") == 0)
and
if(strncmp(var1, "dev", 3) == 0)
Thanks
edit: After testing at home I'm just going to suggest my co-worker changes the datatype to a string. I believe he was comparing a char array of a large size against a string. I put together a program that outputs sizeof, strlen, etc to help us work through it. Thanks to everyone for the help.
Use strcmp() to compare the contents of strings:
if (strcmp(var1, "dev") == 0) {
}
Explanation: in C, a string is a pointer to a memory location which contains bytes. Comparing a char* to a char* using the equality operator won't work as expected, because you are comparing the memory locations of the strings rather than their byte contents. A function such as strcmp() will iterate through both strings, checking their bytes to see if they are equal. strcmp() will return 0 if they are equal, and a non-zero value if they differ. For more details, see the manpage.
You're not working with strings. You're working with pointers.
var1 is a char pointer (const char*). It is not a string. If it is null-terminated, then certain C functions will treat it as a string, but it is fundamentally just a pointer.
So when you compare it to a char array, the array decays to a pointer as well, and the compiler then tries to find an operator == (const char*, const char*).
Such an operator does exist. It takes two pointers and returns true if they point to the same address. So the compiler invokes that, and your code breaks.
IF you want to do string comparisons, you have to tell the compiler that you want to deal with strings, not pointers.
The C way of doing this is to use the strcmp function:
strcmp(var1, "dev");
This will return zero if the two strings are equal. (It will return a value greater than zero if the left-hand side is lexicographically greater than the right hand side, and a value less than zero otherwise.)
So to compare for equality you need to do one of these:
if (!strcmp(var1, "dev")){...}
if (strcmp(var1, "dev") == 0) {...}
However, C++ has a very useful string class. If we use that your code becomes a fair bit simpler. Of course we could create strings from both arguments, but we only need to do it with one of them:
std::string var1 = getenv("myEnvVar");
if(var1 == "dev")
{
// do stuff
}
Now the compiler encounters a comparison between string and char pointer. It can handle that, because a char pointer can be implicitly converted to a string, yielding a string/string comparison. And those behave exactly as you'd expect.
In this code you are not comparing string values, you are comparing pointer values. If you want to compare string values you need to use a string comparison function such as strcmp.
if ( 0 == strcmp(var1, "dev")) {
..
}
"dev" is not a string it is a const char * like var1. Thus you are indeed comparing the memory adresses. Being that var1 is a char pointer, *var1 is a single char (the first character of the pointed to character sequence to be precise). You can't compare a char against a char pointer, which is why that did not work.
Being that this is tagged as c++, it would be sensible to use std::string instead of char pointers, which would make == work as expected. (You would just need to do const std::string var1 instead of const char *var1.
There is more stable function, also gets rid of string folding.
// Add to C++ source
bool string_equal (const char* arg0, const char* arg1)
{
/*
* This function wraps string comparison with string pointers
* (and also works around 'string folding', as I said).
* Converts pointers to std::string
* for make use of string equality operator (==).
* Parameters use 'const' for prevent possible object corruption.
*/
std::string var0 = (std::string) arg0;
std::string var1 = (std::string) arg1;
if (var0 == var1)
{
return true;
}
else
{
return false;
}
}
And add declaration to header
// Parameters use 'const' for prevent possible object corruption.
bool string_equal (const char* arg0, const char* arg1);
For usage, just place an 'string_equal' call as condition of if (or ternary) statement/block.
if (string_equal (var1, "dev"))
{
// It is equal, do what needed here.
}
else
{
// It is not equal, do what needed here (optional).
}
Source: sinatramultimedia/fl32 codec (it's written by myself)
your thinking about this program below
#include <stdio.h>
#include <string.h>
int main ()
{
char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
int n;
puts ("Looking for R2 astromech droids...");
for (n=0 ; n<3 ; n++)
if (strncmp (str[n],"R2xx",2) == 0)
{
printf ("found %s\n",str[n]);
}
return 0;
}
//outputs:
//
//Looking for R2 astromech droids...
//found R2D2
//found R2A6
when you should be thinking about inputting something into an array & then use strcmp functions like the program above ... check out a modified program below
#include <iostream>
#include<cctype>
#include <string.h>
#include <string>
using namespace std;
int main()
{
int Students=2;
int Projects=3, Avg2=0, Sum2=0, SumT2=0, AvgT2=0, i=0, j=0;
int Grades[Students][Projects];
for(int j=0; j<=Projects-1; j++){
for(int i=0; i<=Students; i++) {
cout <<"Please give grade of student "<< j <<"in project "<< i << ":";
cin >> Grades[j][i];
}
Sum2 = Sum2 + Grades[i][j];
Avg2 = Sum2/Students;
}
SumT2 = SumT2 + Avg2;
AvgT2 = SumT2/Projects;
cout << "avg is : " << AvgT2 << " and sum : " << SumT2 << ":";
return 0;
}
change to string except it only reads 1 input and throws the rest out
maybe need two for loops and two pointers
#include <cstring>
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
char name[100];
//string userInput[26];
int i=0, n=0, m=0;
cout<<"your name? ";
cin>>name;
cout<<"Hello "<<name<< endl;
char *ptr=name;
for (i = 0; i < 20; i++)
{
cout<<i<<" "<<ptr[i]<<" "<<(int)ptr[i]<<endl;
}
int length = 0;
while(name[length] != '\0')
{
length++;
}
for(n=0; n<4; n++)
{
if (strncmp(ptr, "snit", 4) == 0)
{
cout << "you found the snitch " << ptr[i];
}
}
cout<<name <<"is"<<length<<"chars long";
}