check if a pointer has some string c++ - c++

I am not good with c++ and I cannot find this anywhere, please apologize me if it is a bad question. I have a pointer and I want to know if some names store in this pointer begins with some specific string. As in python something like (maybe it is a bad example):
if 'Pre' in pointer_name:
This is what I have:
double t = 0;
for (size_t i =0; i < modules_.size(); ++i){
if(module_[i].name() == "pre"){ // here is what I want to introduce the condition
if (modules_[i].status() == 2){
std::cout << module_[i].name() << "exists" << std::endl;
}
}
}

The equivalent of Python 'Pre' in string_name is:
string_name.find("Pre") != std::string::npos // if using string
std::strstr(pointer_name, "Pre") // if using char*
The equivalent of Python string_name.startswith('Pre') ("begins with some specific string") is:
string_name.size() >= 3 && std::equal(string_name.begin(), string_name.begin() + 3, "Pre"); // if using string
string_name.find("Pre") == 0 // less efficient when it misses, but shorter
std::strncmp(pointer_name, "Pre", 3) == 0 // if using char*
In two of those cases, in practice, you might want to avoid using a literal 3 by measuring the string you're searching for.

Check std::string::find, there are enough good examples. If you are using c-style string, use strstr.

You can use the algorithm header file to do most of things usually one liners in python.
In this case though it might be just easier to use string find method .

If your name variable is of type std::string then you can use name().compare("Pre") == 0 for string comparison.
EDIT: Seems I misunderstood the question, for contains you can use string find, as other said.
Using C style strings, char * is not recommended in C++. They are error prone.

Related

replace the occurrence of character with a seq number using boost

How can i replace multiple occurrences of a character with a string containing the occurrence number.
e.g if i have the following expression.
insert into emp values(?,?,?)
I want the following converted string.
insert into emp values(_p_1,_p_2,_p_3)
I am trying this using the boost regular expression.
Can anyone tell me how to achieve this using the boost c++ (with no or minimum iteration).
currently I am using the following approach:
std::wstring q=L"insert into emp values(?,?,?)";
auto loc = q.find(L"?");
auto len = wcslen(L"?");
auto c=1;
while(loc != std::wstring::npos)
{
q.replace(loc, len , L"_p_"+to_wstring(c));
c++;
loc = q.find(L"?");
}
cout<<q.c_str();
Please suggest better and efficient approaches.
I'd just forget regular expressions and trying to do this simple thing with Boost.
It's like asking, "how do I add 1 to a variable using Boost regular expressions"?
Best answer, IMHO, is to instead just use ++ for the task of adding 1, and to use a loop to replace special characters with strings.
string const query_format = "insert into emp values(?,?,?)";
string const params[] = {"_p_1", "_p_2", "_p3"};
string query;
string const* p = params;
for( char const c : query_format )
{
if( c == '?' ) { query += *p++; } else { query += c; }
}
// Use `query`
One might choose to wrap this up as a replace function.
Disclaimer: code not touched by compiler.
If you control the query_format string, why not instead make the placeholders compatible with Boost format.
Re the parenthetical requirement
” with no or minimum iteration
there's iteration involved no matter how you do this. You can hide the iteration behind a function name, but that's all. It's logically impossible to actually avoid the iteration, and it's trivial (completely trivial) to hide it behind a function name.

how to insert a word and use it to make comparison in if condition in c++

i want to use the word i insert to use it to make comparison in if condition to show some word it the comparison is true.
here is my code
#include <iostream>
using namespace std;
int main()
{
char u[5];
cout<<" p " <<" c "<<" U "<<endl;
cout<<" pepsi=5"<<" coca=3"<<" 7-UP=2"<<endl;
cout<<"CHOOSE your drink"<<endl;
cin>>u;
if (u=="pepsi")
cout<<"your choice is pepsi and ur bill is 5 ";
}
First in the future I would suggest trying to be more specific on what your problem is and what you don't understand. Just saying I want to do X and here is my code is giving us very little to work with and we are basically just guessing on what you are having problems with.
Now on to what I believe you are having problems with (I am assuming since you didn't tell us what is going wrong).
In this case you are using a character array with a length of 5. Now when you use character arrays you need to take into account that all the reasonable inputs that that variable might store will actually fit into that character array.
Let's look at pepsi. You might think it would fit but in fact it doesn't because you are forgetting about the null character that is added on the end. This is what it looks like.
u[0] = 'p'
u[1] = 'e'
u[2] = 'p'
u[3] = 's'
u[4] = 'i'
u[5] = '\0'
So as you can see there is actually 6 characters in this word which will cause a overflow. I am assuming this is your problem.
Now how do we fix this? As others have said in the comments if you are using C++ it is probably better for you to use std::string for this problem since it will hide from you most of the problems you have to do deal with when using C style string (What you are using now). Then once you feel more comfortable with the language you can come back and revisit C style strings.
With std::string it would look something like this. Remember that when testing strings case matters (IE "string" is not the same as "String").
std::string choice;
std::cin >> choice;
if (choice == "pepsi")
{
std::cout << "You selected pepsi!" << std::endl;
}
Hope that helps a little and fixes your problems.

Task using for (strcmp aswell)

This is the code that I have now:
int main() {
char stupac1, stupac2;
for (stupac1 = 'A'; stupac1 <= 'Z'; ++stupac1)
{
for (stupac2 = 'a'; stupac2 <= 'z'; ++stupac2)
// between the caps and the non caps there are 32 letters (ASCII code)
if(strcmp (reinterpret_cast <const char*> (stupac1),
reinterpret_cast <const char*> (stupac2)) == 32 )
{
cout <<stupac1 << stupac2 << endl;
}
else
{
cout << "These letters suck" << endl;
}
}
return 0;
}
The task: I need to write a program with 2 consecutive loops that will make a table which has the letters A-Z and a-z in 2 columns.
I need to use for, but strcmp can be removed if is not necessary. I was trying something but nothing is printed when I run this code and it crashes.
In C++, characters (char) are scalar values just like int, not strings. For example 'A' is equal to 65, assuming an ASCII/Unicode system. To test for equality, use the == operator.
It's quite easy to "count" from A to Z in ASCII, but not all C++ implementations are ASCII. For bonus points with your teacher, point out that the program wouldn't run under EBCDIC.
Also, before getting too accustomed to char * strings, be aware that real C++ programs almost exclusively use std::string, which also uses the == operator for comparison.
strcmp (reinterpret_cast <const char*> (stupac1), reinterpret_cast <const char*>(stupac2))
This invokes undefined behavior, as the arguments to strcmp should be null-terminated strings, but what you're passing are not null-terminated.
Since it is not clear what you're trying to do, I'm not going to suggest an alternative and correct solution.
Single chars are just like a smaller version of int, so you can compare them or subtract their values, just like with ints.
A much simpler version of your test would be
if (stupac2 - stupac1 == 32)
See, much easier. :-)
Whenever you seem to need reinterpret_cast you are probably trying things the wrong way.

C++: check whether a word is spelled correctly

I'm looking for an easy way to check whether a certain string is a correctly-spelled English word. For example, 'looked' would return True while 'hurrr' would return False. I don't need spelling suggestions or any spelling-correcting features. Just a simple function that takes a string and returns a boolean value.
I could do this easily with Python using PyEnchant, but it seems you have to compile the library yourself if you want to use it with MS Visual C++.
PyEnchant is based on Enchant, which is a C library providing C and C++ interfaces. So you can just use that for C++. The minimal example will be something like this:
#include <memory>
#include <cstdio>
#include "enchant.h"
#include "enchant++.h"
int main ()
{
try
{
enchant::Broker *broker = enchant::Broker::instance ();
std::auto_ptr<enchant::Dict> dict (broker->request_dict ("en_US"));
const char *check_checks[] = { "hello", "helllo" };
for (int i = 0; i < (sizeof (check_checks) / sizeof (check_checks[0])); ++i)
{
printf ("enchant_dict_check (%s): %d\n", check_checks[i],
dict->check (check_checks[i]) == false);
}
} catch (const enchant::Exception &) {
return 1;
}
}
For more examples/tests, see their SVN repository.
If you want to implement such function on your own, you'll need a database to query in order to find out whether a given word is valid (usually a plain text file is enough, like /usr/share/dict/words on Linux).
Otherwise you could rely upon a third party spellcheck library that does just that.
You could take one of the GNU dictionaries out there (like /usr/share/dict/words as mentioned) and build it into an appropriate data structure that'll give you fast lookup and membership checking depending on your performance needs, something like a directed acyclic word graph or even just a trie might be sufficient.
You'd need a word list, for starters. (/usr/share/dict/words maybe?)
You should read your word list into a std::set. Then a correct-spelling test consists simply of checking all the user input words for whether or not they are in the set.
bool spell_check(std::string const& str)
{
std::cout << "Is '" << str << "' spelled correctly? ";
std::string input;
std::getline(input);
return input[0] == 'y' || input[0] == 'Y';
}

Read file and extract certain part only

ifstream toOpen;
openFile.open("sample.html", ios::in);
if(toOpen.is_open()){
while(!toOpen.eof()){
getline(toOpen,line);
if(line.find("href=") && !line.find(".pdf")){
start_pos = line.find("href");
tempString = line.substr(start_pos+1); // i dont want the quote
stop_pos = tempString .find("\"");
string testResult = tempString .substr(start_pos, stop_pos);
cout << testResult << endl;
}
}
toOpen.close();
}
What I am trying to do, is to extrat the "href" value. But I cant get it works.
EDIT:
Thanks to Tony hint, I use this:
if(line.find("href=") != std::string::npos ){
// Process
}
it works!!
I'd advise against trying to parse HTML like this. Unless you know a lot about the source and are quite certain about how it'll be formatted, chances are that anything you do will have problems. HTML is an ugly language with an (almost) self-contradictory specification that (for example) says particular things are not allowed -- but then goes on to tell you how you're required to interpret them anyway.
Worse, almost any character can (at least potentially) be encoded in any of at least three or four different ways, so unless you scan for (and carry out) the right conversions (in the right order) first, you can end up missing legitimate links and/or including "phantom" links.
You might want to look at the answers to this previous question for suggestions about an HTML parser to use.
As a start, you might want to take some shortcuts in the way you write the loop over lines in order to make it clearer. Here is the conventional "read line at a time" loop using C++ iostreams:
#include <fstream>
#include <iostream>
#include <string>
int main ( int, char ** )
{
std::ifstream file("sample.html");
if ( !file.is_open() ) {
std::cerr << "Failed to open file." << std::endl;
return (EXIT_FAILURE);
}
for ( std::string line; (std::getline(file,line)); )
{
// process line.
}
}
As for the inner part the processes the line, there are several problems.
It doesn't compile. I suppose this is what you meant with "I cant get it works". When asking a question, this is the kind of information you might want to provide in order to get good help.
There is confusion between variable names temp and tempString etc.
string::find() returns a large positive integer to indicate invalid positions (the size_type is unsigned), so you will always enter the loop unless a match is found starting at character position 0, in which case you probably do want to enter the loop.
Here is a simple test content for sample.html.
<html>
<a href="foo.pdf"/>
</html>
Sticking the following inside the loop:
if ((line.find("href=") != std::string::npos) &&
(line.find(".pdf" ) != std::string::npos))
{
const std::size_t start_pos = line.find("href");
std::string temp = line.substr(start_pos+6);
const std::size_t stop_pos = temp.find("\"");
std::string result = temp.substr(0, stop_pos);
std::cout << "'" << result << "'" << std::endl;
}
I actually get the output
'foo.pdf'
However, as Jerry pointed out, you might not want to use this in a production environment. If this is a simple homework or exercise on how to use the <string>, <iostream> and <fstream> libraries, then go ahead with such a procedure.