How to compare char variables (c-strings)? - c++

#include <iostream>
using namespace std;
int main() {
char word[10]="php";
char word1[10]="php";
if(word==word1){
cout<<"word = word1"<<endl;
}
return 0;
}
I don't know how to compare two char strings to check they are equal. My current code is not working.

Use strcmp.
#include <cstring>
// ...
if(std::strcmp(word, wordl) == 0) {
// ...
}

Use std::string objects instead:
#include <iostream>
#include <string>
using namespace std;
int main() {
string word="php";
string word1="php";
if(word==word1){
cout<<"word = word1"<<endl;
}
return 0;
}

To justify c++ tag you'd probably want to declare word and word1 as std::string. To compare them as is you need
if(!strcmp(word,word1)) {

word and word1 in your submitted code are pointers. So when you code:
word==word1
you are comparing two memory addresses (which isn't what you want), not the c-strings they point to.

#include <iostream>
**#include <string>** //You need this lib too
using namespace std;
int main()
{
char word[10]="php";
char word1[10]="php";
**if(strcmp(word,word1)==0)** *//if you want to validate if they are the same string*
cout<<"word = word1"<<endl;
*//or*
**if(strcmp(word,word1)!=0)** *//if you want to validate if they're different*
cout<<"word != word1"<<endl;
return 0;``
}

Related

I'am working on a C++ program where I'am facing a error while execution of if-else statement [duplicate]

#include <iostream>
using namespace std;
int main() {
char word[10]="php";
char word1[10]="php";
if(word==word1){
cout<<"word = word1"<<endl;
}
return 0;
}
I don't know how to compare two char strings to check they are equal. My current code is not working.
Use strcmp.
#include <cstring>
// ...
if(std::strcmp(word, wordl) == 0) {
// ...
}
Use std::string objects instead:
#include <iostream>
#include <string>
using namespace std;
int main() {
string word="php";
string word1="php";
if(word==word1){
cout<<"word = word1"<<endl;
}
return 0;
}
To justify c++ tag you'd probably want to declare word and word1 as std::string. To compare them as is you need
if(!strcmp(word,word1)) {
word and word1 in your submitted code are pointers. So when you code:
word==word1
you are comparing two memory addresses (which isn't what you want), not the c-strings they point to.
#include <iostream>
**#include <string>** //You need this lib too
using namespace std;
int main()
{
char word[10]="php";
char word1[10]="php";
**if(strcmp(word,word1)==0)** *//if you want to validate if they are the same string*
cout<<"word = word1"<<endl;
*//or*
**if(strcmp(word,word1)!=0)** *//if you want to validate if they're different*
cout<<"word != word1"<<endl;
return 0;``
}

How to check if a string ends with 'ed' in C++;

How to write a program that reads 5 strings from user input and prints only those strings that end with the letter ‘ed’ in C++. Need help!
The solution is rather straightforward.
First we define a container that can contain 5 std::string. For that we use a std::vector together with a constructor to reserve space for the 5 elements.
Then we copy 5 strings from the console (from user input) into the vector.
And, last, we copy elements out of the std::vector to std::cout, if the strings end with "ed".
Because of the simplicity of the program, I cannot explain much more . . .
Please see.
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <iterator>
constexpr size_t NumberOfTexts = 5U;
int main()
{
// Define a container that can hold 5 strings
std::vector<std::string> text(NumberOfTexts);
// Read 5 strings from user
std::copy_n(std::istream_iterator<std::string>(std::cin), NumberOfTexts, text.begin());
// Print the strings with ending "ed" to display
std::copy_if(text.begin(), text.end(), std::ostream_iterator<std::string>(std::cout,"\n"), [](const std::string& s){
return s.size()>=2 && s.substr(s.size()-2) == "ed";
});
return 0;
}
Simple solution,
#include<iostream>
using namespace std;
bool endsWith(const std::string &mainStr, const std::string &toMatch)
{
if(mainStr.size() >= toMatch.size() &&
mainStr.compare(mainStr.size() - toMatch.size(), toMatch.size(), toMatch) == 0)
return true;
else
return false;
}
int main()
{
string s[5];
for(int i=0;i<5;i++)
{
cin>>s[i];
}
for(int i=0;i<5;i++)
{
if(endsWith(s[i],"ed"))
cout<<s[i]<<endl;
}
}
Hope This might Helps:)

Segmentation fault in reversing string program

I am trying to reverse a string. Can someone explain me why this is giving me segmentation fault?
#include <iostream>
#include <string>
using namespace std;
int main(){
string str,rstr;
int len=str.length(),i=0;
cin>>str;
while(str[i]!='\0'){
rstr[--len]=str[i++];
}
rstr[str.length()]='\0';
cout<<rstr;
return 0;
}
P.S.: Need to reverse it without using library functions.
If you want to go the way you are doing it, for practice purposes, try this changes and start from there
#include <iostream>
#include <string>
using namespace std;
int main(){
string str,rstr;
cin>>str; // --- Moved this line up
rstr = str; // --- Added this line
int len=str.length(),i=0;
while(str[i]!='\0'){
rstr[--len]=str[i++];
}
rstr[str.length()]='\0';
cout<<rstr;
return 0;
}
Or just use reverse iterator
std::string s = "Hello";
std::string r(s.rbegin(), s.rend());
str is nothing but a declared string here:
int len=str.length(),i=0;
So you can't do str.length()
Do something like:
#include <iostream>
#include <string>
using namespace std;
int main(){
string str,rstr;
int len,i=0;
cin>>str;
len = str.length();
while(str[i]!='\0'){
rstr[i++]=str[--len];
}
rstr[str.length()]='\0';
cout<<rstr;
return 0;
}

Putting String array in parameter, then comparing the elements to literal strings error?

Let's say I have an array
string test = {"test1, "test2"}
I have my function
void testing(string test){
for(int i = 0; i < 2; i++){
if(test[i] == "test1"){
cout << "success" << endl;
}
}
}
But when I compile this, I get an error...why is that?
Is there a different approach?
Your test variable should be declared as an array type
string test[] = {"test1", "test2"};
You also need to change the function signature from
void testing(string test)
to
void testing(string* test){
the code you wrote is not going to compile because of wrong declaration of string array.
replace
string test = {"test1, "test2"};
with
string test[]={"test1, "test2"};
The following code uses the array in place without function
#include <iostream>
#include <string>
using namespace std;
string test[]={"test1, "test2"};
for(auto& item:test)
{
cout<<item<<endl;
}
I think the best way to get this working with function is to use vector
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void testing(const vector<string>& strings)
{
for (auto& item : strings)
{
cout << item << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
vector<string> strings = { "str1", "str2", "str3" };
testing(strings);
cin.get();
return 0;
}

C string comparison problem in c++

I've been having trouble with comparison in my c++ program. This is the boiled down version.
#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;
int main(int argc, char *argv[])
{
if(argc>2){cout<<"3+Args"<<endl;}else//???
if(argc==2){
cout<<"2args"<<endl;
if(argv[1]=="/hide-icons"){}
if(argv[1]=="/show-icons"){}
if(argv[1]=="/reinstall"){setAsDefault();}
if(argv[1]=="/?"){showPossibleCommands();}
if(argv[1]=="/1"){cout<<"go"<<endl;FirstRun();}
}else{showPossibleCommands();cout<<argv[0]<<endl;}
return 0;
}
When I run "programname.exe /1", my program writes "2args" but not "go". Am I missing something obvious?
argv[1] is a char*, so by testing with == you're checking if the pointer points to the same spot as the start of the various string constants you're using... which is not going to be the case. To compare contents instead, use strcmp.
The problem is, that your code compares the pointers to the strings, not the stings itself.
You have to replace the compares with calls to the string-compare function.
E.g.
if(argv[1]=="/1"){cout<<"go"<<endl;FirstRun();}
becomes
if(strcmp(argv[1],"/1") == 0) {cout<<"go"<<endl;FirstRun();}
You may have to include string.h to get the strcmp prototype into your code.
Another option is to convert the C-style arguments into a much more friendly vector of strings and process them instead:
#include <string>
#include <vector>
typedef std::vector<std::string> parameter_list;
int
cpp_main(std::string const& program_name, parameter_list const& params) {
for (parameter_list::const_iterator arg=params.begin(); arg!=params.end(); ++arg) {
if (*arg == "/hide-icons") {
} else if (*arg == "/show-icons") {
} else if (*arg == "/reinstall") {
set_as_default();
} else if (*arg == "/?") {
show_help(program_name);
} else if (*arg == "/1") {
first_run();
} else {
show_help(program_name);
}
}
return 0;
}
int
main(int argc, char **argv) {
return cpp_main(argv[0], parameter_list(&argv[1], &argv[argc]));
}