Hello? I want to know how can I find number in my string code.
This is my c++ code.
string firSen;
cout<<"write the senctence : "<<endl;
getline(cin,firSen);
int a=firSen.find("pizza");
int b=firSen.find("hamburger");
int aa=firSen.find(100);
int bb=firSen.find(30);
I want to write
I want to eat pizza 100g, hamburger 30g!!
and I want to know 100 and 30 address.
I know how to find pizza and hamburger address.(It's the right code)
but I don't know how to find number..(I think int aa=firSen.find(100); int bb=firSen.find(30); is wrong code)
Could you help me?
The std::string::find() function takes a std::string or a const char* as valid search keys.
If you want to search for 'generic numbers' you'll have to convert them to a std::string or use a const char* literal
size_type aa=firSen.find("100");
or
int num = 100;
size_type aa=firSen.find(std::to_string(num));
See the std::to_string() function reference
As it looks from your input sample, you don't know the numeric values beforehand, thus looking up something like
size_type aa=firSen.find("100");
renders useless.
What you actually need is some decent parser, that enables you reading the numeric values after some certain keywords, that require a numeric attribute (like weight in your sample).
The simplest way might be, to find your keywords like "hamburger" or "pizza", and move on from the found position, to find the next digit ('0-9'), and extract the number from that position.
Using std::regex as proposed in #deeiip's answer, might be a concise solution for your problem.
I'd use this in your situation (if I was searching for just a number, not a specific number):
std::regex rgx("[0-9]+");
std::smatch res;
while (std::regex_search(firSen, res, rgx)) {
std::cout << res[0] << std::endl;
s = res.suffix().str();
}
This is c++11 standard code using <regex>. What it does is: search for any occurence of a number. This is what [0-9]+ means. And It keep on searching for this pattern in your string.
This solution should only be used when I dont know what number I'm expecting otherwise it'll be much more expensive than other solution mentioned.
Related
I need help with C++ <string.h> char tables.... How to cut word from sentence, using "*" operator, with no strstr? For example: "StackOverFlow is online website". I have to cut off "StackOverFlow" and leave in table "is online website" using operator, with no strstr. I couldn't find it anywhere.
Mostly like:
char t[]
int main
{
strcpy(t,"Stackoverflow is online website");
???
(Setting first char to NULL, then strcat/strcpy rest of sentence into table)
}
Sorry for English problems/Bad naming... I'm starting to learning C++
You can do something like this. Explain better what you need, please.
char szFirstStr[] = "StackOverflow, flowers and vine.";
strcpy(szFirstStr, szFirstStr + 15);
std::cout << szFirstStr << std::endl;
Will output "flowers and vine".
Using c strings is not good style for C++ programmer, use std::string class.
Your code is obviously syntactically incorrect, but I guess you are aware of that.
Your variable t is really a char array and you have a pointer that points to the first character of that char array, like you have a pointer that points to the first character of your null terminated string. What you can do is to change the pointer value to point to the new starting point of your string.
You can either do that, or if you indeed use an array, you can copy from the pointer of the new starting point you wish to use. So if the data you wish to copy resides in memory pointed to by:
const char* str = "Stackoverflow is an online website";
This looks like the following in memory:
Stackoverflow is an online website\0
str points to: --^
If you want to point to a different starting point you can alter the pointer to point at a different starting location:
Stackoverflow is an online website\0
str + 14 points to: --------------^
You can pass the address of the "i" to your strcpy, like so:
strcpy(t, str + 14);
Obviously it is not certain that you know the size to cut off without an analysis (the 14), what you might do is search through the string for the first character following a white space.
// Notice that this is just a sample of a search that could be made
// much more elegant, but I will leave that to you.
const char* FindSecondWord(const char* strToSearch) {
// Loop until the end of the string is reached or the first
// white space character
while (*strToSearch && !isspace(*strToSearch)) strToSearch++;
// Loop until the end of the string is reached or the first
// non white space character is found (our new starting point)
while (*strToSearch && isspace(*strToSearch)) strToSearch++;
return strToSearch;
}
strcpy(t, FindSecondWord("Stackoverflow is an online website"));
cout << t << endl;
This will output: is an online website
Since this is most likely a school assignment, I will skip the lecture on more modern C++ string handling, as I expect this has something to do with learning pointers. But obviously this is very low level modification of a string.
As a beginner why make it harder then it really have to be?
Use std::string
and
substr()
Link
I'm working on creating a program that will take a fraction and reduce it to it's lowest terms. I'm using a tokenizer to parse through the string (In my case I'm reading in a string) and separate the numerator from the denominator.
I'm getting the following error, and am looking for an explanation to why it's happening. I've looked up people with similar problems, but I'm still a beginner looking for a basic explanation and suggestion for an alternative way to solve it.
RationalNum() // Default
:numerator(0), denominator(1){}
RationalNum(int num) // Whole Number
:numerator(num), denominator(1){}
RationalNum(int num, int denom) // Fractional Number
:numerator(num), denominator(denom){}
RationalNum(string s)
{
int num = 0;
char str[] = s;
}
I know the problem lies in the setting the char array to s.
Thanks for taking the time to look at this.
You are trying to initialise an array of char to a std::string, which is an object. The literal meaning of the error is that the compiler is expecting an initialisation that looks something like this :
char str[] = {'1','2','3','4'};
However, since you are planning on string manipulation anyway, you would have a much easier time just keeping the string object rather than trying to assign it to a char array.
Instead of building your parser from scratch, you can use string stream and getline. with '/' as your delimiter. You can initialise an std::stringstream with a string by passing it as an argument when constructing it. You can also use another stringstream to convert a string into a number by using the >> operator.
This question already has an answer here:
std::stringstream strange behaviour
(1 answer)
Closed 9 years ago.
I have a string with lots of different characters similar to: "$: " "213.23453"
How do i extract the double value 213.23453 and store it in a variable, it's C++/C and i cant use lambdas.
You can use "poor man's regex" of the sscanf function to skip over the characters prior to the first digit, and then reading the double, like this:
char *str = "\"$: \" \"213.23453\"";
double d;
sscanf(str, "%*[^0-9]%lf", &d);
Note the asterisk after the first percentage format: it instructs sscanf to read the string without writing its content into an output buffer.
Here is a demo on ideone.
Use a regular expression.
[$]?[0-9]*(\.)?[0-9]?[0-9]?
This should match those with a $ sign and those without.
Boost.Regex is a very good regular expression library
Personally, I find Boost.Xpressive much nicer to work with. It is a header-only library and it has some nice features such as static regexes (regexes compiled at compile time).
If you're using a C++11 compliant compiler, use std::regex unless you have good reason to use something else.
Pure C++ solution could be to manually cut off the trash characters preceding the number (first digit identified by std::isdigit) and then just construct a temporary istringstream object to retrieve the double from:
std::string myStr("$:. :$$#&*$ :213.23453$:#$;");
// find the first digit:
int startPos = 0;
for (; startPos < myStr.size(); ++startPos)
if (std::isdigit(myStr[startPos])) break;
// cut off the trash:
myStr = myStr.substr(startPos, myStr.size() - startPos);
// retrieve the value:
double d;
std::istringstream(myStr) >> d;
but C-style sscanf with appropriate format specified would suffice here as well :)
is there anyway to find out how many times a word repeated in a text .
the text is in character arrays (char[])
text = this is a book,and this book
is about book.
word = book
result = 3
Because this is clearly homework and not tagged as such, I'll give you a solution you clearly can't submit as your assignment because your teacher will know you got it on the internet.
There were no requirements such as ignoring punctuation, so I've allowed myself to write a version that only works for clearly separated words and thus inserted spaces in your sample text string.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
// Count clearly separated occurrences of `word` in `text`.
std::size_t count ( const std::string& text, const std::string& word )
{
std::istringstream input(text);
return (std::count(std::istream_iterator<std::string>(input),
std::istream_iterator<std::string>(), word));
}
int main ( int, char ** )
{
const char text[] = "this is a book , and this book is about book .";
const char word[] = "book";
std::cout << count(text, word) << std::endl;
}
Output:
3
You might want to implement this using std::string and here is a sample for you to start from.
The simplest way would be to loop through the string, counting the number of times that you find the word that you're looking for. I'm sure that you could use a function in <algorithm> to do it fairly easily, but if you have to ask whether it's possible to do this in C++, I wouldn't think that you're advanced enough to try using the algorithm library, and doing it yourself would be more instructional anyway.
I would suggest using std::string though if you're allowed to (since this question does sound like homework, which could carry additional restrictions). Using std::string is easier and less error-prone than char arrays. It can be done with both though.
It is possible.
You have an array of characters. Try to do the search on a piece of paper, character by character:
First character is a T. This is not a b, so it can't be the first character of "book"
Second character is a h, so again, it is not b...
[...]
The next character is a b... Oah, this could be it. Is the next character a o? YES!!! And then next another o???... etc. etc..
When you can do it this way, you will be able to use C++ to do it.
Remember that you can access the n-th character in an array by using the [] operator:
char c = array[5] ; // c is the 6th character in the array
Now, going toward the C++ way would be, at first, to use a std::string instead of an array of chars, and use the strings methods. Google for std::string methods, and I guess you should find somes that you could use...
So you should manage to write some code that will iterate each character until the end
I guess this should be more than enough.
The point of your homework (because everyone here knows this is a homework question) is more about searching for the solution than finding it: This is not rote learning.
I doubt anyone on Stack Overflow remembers the solution to this classical problem. But I guess most will know how to find one solution. You need to learn the "how to find" mindset, so get your compiler and try again...
P.S.: Of course, if you know little or nothing of C++, then you're screwed, and you could start by Googling some C++ Tutorials.
I'm writing a small command-line program that asks the user for polynomials in the form ax^2+bx^1+cx^0. I'm going to parse the data later but for now I'm just trying to see if I can match the polynomial with the regular expression(\+|-|^)(\d*)x\^([0-9*]*)My problem is, it doesn't match multiple terms in the user-entered polynomial unless I change it to((\+|-|^)(\d*)x\^([0-9*]*))*(the difference is the entire expression is grouped and has an asterisk at the end). The first expression works if I type something such as "4x^2" but not "4x^2+3x^1+2x^0", since it doesn't check multiple times.
My question is, why won't Boost.Regex'sregex_match()find multiple matches within the same string? It does in the regular expression editor I used (Expresso) but not in the actual C++ code. Is it supposed to be like that?
Let me know if something doesn't make sense and I'll try to clarify. Thanks for the help.
Edit1: Here's my code (I'm following the tutorial here: http://onlamp.com/pub/a/onlamp/2006/04/06/boostregex.html?page=3)
int main()
{
string polynomial;
cmatch matches; // matches
regex re("((\\+|-|^)(\\d*)x\\^([0-9*]*))*");
cout << "Please enter your polynomials in the form ax^2+bx^1+cx^0." << endl;
cout << "Polynomial:";
getline(cin, polynomial);
if(regex_match(polynomial.c_str(), matches, re))
{
for(int i = 0; i < matches.size(); i++)
{
string match(matches[i].first, matches[i].second);
cout << "\tmatches[" << i << "] = " << match << endl;
}
}
system("PAUSE");
return 0;
}
You're using the wrong thing -- regex_match is intended to check whether a (single) regex matches the entirety of a sequence of characters. As such, you need to either specify a regex that matches the whole input, or use something else. For your situation, it probably makes the most sense to just modify the regex as you've already done (group it and add a Kleene star). If you wanted to iterate over the individual terms of the polynomial, you'd probably want to use something like a regex_token_iterator.
Edit: Of course, since you're embedding this into C++, you also have to double all your backslashes. Looking at it, I'm also a little confused about the regex you're using -- it doesn't look to me like it should really work quite right. Just for example, it seems to require a "+", "-" or "^" at the beginning of a term, but the first term won't normally have that. I'm also somewhat uncertain why there would be a "^" at the beginning of a term. Since the exponent is normally omitted when it's zero, it's probably better to allow it to be omitted. Taking those into account, I get something like: "[-+]?(\d*)x(\^([0-9])*)".
Incorporating that into some code, we can get something like this:
#include <iterator>
#include <regex>
#include <string>
#include <iostream>
int main() {
std::string poly = "4x^2+3x^1+2x";
std::tr1::regex term("[-+]?(\\d*)x(\\^[0-9])*");
std::copy(std::tr1::sregex_token_iterator(poly.begin(), poly.end(), term),
std::tr1::sregex_token_iterator(),
std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}
At least for me, that prints out each term individually:
4x^2
+3x^1
+2x
Note that for the moment, I've just printed out each complete term, and modified your input to show off the ability to recognize a term that doesn't include a power (explicitly, anyway).
Edit: to collect the results into a vector instead of sending them to std::cout, you'd do something like this:
#include <iterator>
#include <regex>
#include <string>
#include <iostream>
int main() {
std::string poly = "4x^2+3x^1+2x";
std::tr1::regex term("[-+]?(\\d*)x(\\^[0-9])*");
std::vector<std::string> terms;
std::copy(std::tr1::sregex_token_iterator(poly.begin(), poly.end(), term),
std::tr1::sregex_token_iterator(),
std::back_inserter(terms));
// Now terms[0] is the first term, terms[1] the second, and so on.
return 0;
}