In the following code, I am attempting to add elements to a vector of strings, ints, and doubles but when I output the vector's size, it never moves past 1. This leads me to believe it's not adding elements, but instead changing the first element?
// Need to show this for the code I'm having issues with
struct Store_Info{ // Stores all info for a given item
string store_name;
string location;
// vector<string> = item | vector<int> = stock || vector<double> = price
pair<pair<vector<string>, vector<int>>, vector<double>> item_stock_price;
Store_Info() = default;
Store_Info(string, string);
string how_many(int);
};
void stock_info(vector<Store_Info> &stores, int n_stores){ // This is the code I need help with
for (int i(0); i<n_stores; i++){
string name; string loc;
int counter(0);
bool active(true);
while(active){
string line;
std::getline (cin,line);
if (line == "")
active = false;
else if (counter == 0){
name = line;
counter++;
}
else if (counter == 1){
loc = line;
stores[i] = Store_Info(name, loc);
counter ++;
}
else{
regex reg{R"((\w+),(\d+),\W(\d+.\d+))"}; // From professor's piazza post
std::smatch m;
std::regex_match(line, m, reg);
Store_Info current_store = stores[i];
pair itemStock = std::get<0>(current_store.item_stock_price);
std::get<0>(itemStock).push_back(m[1].str()); // Defines item name
std::get<1>(itemStock).push_back(std::stoi(m[2].str())); // Defines amount in stock
std::get<1>(current_store.item_stock_price).push_back(std::stod(m[3].str())); // Defines price
//cout << std::get<1>(current_store.item_stock_price).capacity();
}
}
}
}
Sorry if this is formatted poorly, this is my first post.
Any help is appreciated, thank you!
edit: Might be helpful to know what's being inputted..
Using standard input, the function reads in this:
(int) Stores:
(Name of a store)
(A location)
(item name),(quantity),$(price)
Ex.)
2 Stores:
Local Grocery
California
Apples,2,$1.20
Mall
Michigan
Pizza,3,$4.00
Cake,1,$10.45
Please consider to change you code to something like this.
Using nested pair's is way too confusing. Then at least use std::tuple.
Also you need to use reference to the struct and not its copy !
struct Item {
string name; // Defines item name
int amount; // Defines amount in stock
double price; // Defines price
}
struct Store_Info { // Stores all info for a given item
string store_name;
string location;
// vector<string> = item | vector<int> = stock | vector<double> = price
vector<Item> items;
Store_Info() = default;
Store_Info(string, string);
string how_many(int);
};
void stock_info(vector<Store_Info> &stores, int n_stores){ // This is the code I need help with
for (int i(0); i<n_stores; i++){
string name; string loc;
int counter(0);
bool active(true);
while(active){
string line;
std::getline (cin,line);
if (line == "")
active = false;
else if (counter == 0){
name = line;
counter++;
}
else if (counter == 1){
loc = line;
stores[i] = Store_Info(name, loc);
counter ++;
}
else{
regex reg{R"((\w+),(\d+),\W(\d+.\d+))"}; // From professor's piazza post
std::smatch m;
std::regex_match(line, m, reg);
Store_Info ¤t_store = stores[i]; // need to be reference and not the copy !
// item name | amount | price
current_store.items.emplace_back(m[1].str(), std::stoi(m[2].str()), std::stod(m[3].str()));
}
}
}
}
Not sure about other bugs or problems because this code is not run-able.
I am working on my first web app (weather visualization) that requires some light c++ on the back end. I am using wget to download the raw text, and c++ console to parse the data and it then writes HTML. This works great so far.
METAR is basically raw weather data from a station. (Time, Date, Conditions, Temp etc). The one I am using currently is :
2018/08/10 08:09
KBAZ 100809Z AUTO 00000KT 10SM BKN012 26/23 A3002 RMK AO2 T02610233
I have been able to store each set of data into different variables. The set I am looking at with the issue is the "26/23" above, which is the temperature and dew point in Celsius.
So far I have a string called tempAndDewpoint with "26/23" stored in it... I am using substr(0,2) to return the just temperature in a new string called temperature. (since the first number is temperature). This works great.
My question is, what happens if the temperature is below 10, like 9? I could no longer use substring(0,2) because that would then return "9/" as the current temperature.
I hope to find some guidance with this that is not too complicated for me to duplicate. I wasn't even sure what to name this question as I am not sure what this issue is called. Surely it must be common?
Beware: Negative temperatures in METAR are prefixed with M. So these are valid temp groups: 5/M2 or M8/M12 (negative dew points are in fact icing points). So I would not use a custom parser here:
struct TTD {
short int t;
short int td;
bool parse(const char *tempAndDewpoint) {
const char *next;
t = parse_partial(tempAndDewpoint, &next);
if (*next != '/') return false;
td = parse_partial(next + 1, &next);
return (*next == '\0');
}
private:
static short int parse_partial(const char *beg, const char **next) {
bool neg = false;
short int val = 0;
if (*beg == 'M') {
neg = true;
beg += 1;
}
while (*beg >= '0' && *beg <= '9') {
val = val * 10 + (*beg - '0');
beg += 1;
}
*next = beg;
if (neg) val = -val;
return val;
}
};
The simple solution is to not store as a string at all. Split the string into two independent numbers. As stated in the other answer you do need to take care of "M" being a prefix for negative numbers but there is no read to parse the numbers by hand:
int parseNum(const std::string& str)
{
size_t pos;
int num;
if (!str.empty() && str.front() == 'M')
{
num = -std::stoi(str.substr(1), &pos);
if (pos != str.size() - 1)
{
throw std::invalid_argument("invalid input");
}
}
else
{
num = std::stoi(str, &pos);
if (pos != str.size())
{
throw std::invalid_argument("invalid input");
}
}
return num;
}
size_t slash = tempAndDewpoint.find("/");
if (slash == std::string::npos)
{
throw std::invalid_argument("invalid input");
}
int temp = parseNum(tempAndDewpoint.substr(0, slash));
int dew = parseNum(tempAndDewpoint.substr(slash + 1));
I've been studying everything I've gone over in my first semester of programming. I have a final coming up so I've been trying to write sample programs combining everything I've learned to prepare. The program below is supposed to read in names from a file, sort them via bubble search, and then prompt the user to enter a name, which the binary search will look for and tell you if the person is a friend or not.
My problem is, when I type a name, I am only prompted to type the name again. There is no output.
Please keep in mind that everything in here is mostly what I've learned so far (so I do not know how to use vectors, pointers, etc).
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void bubblesort(string[], const int);
void search(string[], const int);
int sub = 0;
int main()
{
const int maxsize = 100;
string friendArray[maxsize];
ifstream friends;
friends.open("myFriends.dat");
while (sub < maxsize && getline(friends, friendArray[sub]))
sub++;
bubblesort(friendArray, sub);
search(friendArray, maxsize);
system("pause");
return 0;
}
void bubblesort(string *array, const int size)
{
bool swap;
string temp;
do
{
swap = false;
for (int count = 1; count < (size - 1); count++)
{
if(array[count-1] >array[count])
{
temp = array[count-1];
array[count-1] = array[count];
array[count] = temp;
swap = true;
}
}
}
while(swap);
}
void search(string *array, int size)
{
int first = 0;
int last = size - 1;
int middle;
string name;
bool friends = false;
do
{
cout<<"Please enter a name or END to terminate:";
cin>>name;
}
while(!friends && first <= last && name != "END");
{
middle = (first + last) / 2;
if (array[middle] == name)
{
friends = true;
cout<<array[middle]<<" is my friend."<<endl;
}
else if (array[middle] > name)
last = middle - 1;
else
last = middle + 1;
}
}
I don't want to give too much away, since it's homework, so I'll move some of your code around, keeping it as close as possible, and show you why it currently won't work.
At the moment you're kind of thinking the do...while loop is some sort of double block, it's not. The code after the while(...); in your code will only be executed once, after you break out of the do...while loop, it's in no way connected. You're going to need two loops, an outer one that prompts for names, and an inner one that looks for that name in your list.
You're also not resetting friends and last after asking the user to enter another name. An easy fix is to move your declarations (which contain initialisations) inside the first loop.
This is what your code will look like after mostly rearranging it and apply the above changes:
void search(string *array, int size)
{
string name;
cout<<"Please enter a name or END to terminate:";
cin>>name;
while (name != "END")
{
bool friends = false;
int first = 0;
int last = size - 1;
int middle;
while(!friends && first <= last)
{
middle = (first + last) / 2;
if (array[middle] == name)
{
friends = true;
cout<<array[middle]<<" is my friend."<<endl;
}
else if (array[middle] > name)
last = middle - 1;
else
last = middle + 1;
}
cout<<"Please enter another name or END to terminate:";
cin>>name;
}
}
There's two different prompts this time, so that if the user enters "END", the outside loop terminates immediately, rather than having to add an extra check inside the loop.
Also, as with your other question, search(friendArray, maxsize); should be search(friendArray, sub);, for the reason I told you last time - sub is a count of valid items in the array, maxsize is the capacity of the array.
NOTE: If the name doesn't exist in your list, it'll cause an infinite loop. I'll let you work that out since it's homework and I don't want to change any of your actual logic. A hint though is to think about what's actually happening - if a value doesn't exist you'll just keep incrementing and decrementing last around the area where the value should be if it existed.
Perhaps if your logic incorporated first being modified somewhere, so that the condition first <= last would fail and you'd break out of the loop...
Your do while statement is wrong, it run this order:
do
{
cout<<"Please enter a name or END to terminate:";
cin>>name;
}
while(!friends && first <= last && name != "END");
And then this block:
{
middle = (first + last) / 2;
if (array[middle] == name)
{
friends = true;
cout<<array[middle]<<" is my friend."<<endl;
}
else if (array[middle] > name)
last = middle - 1;
else
last = middle + 1;
}
Modify it:
do
{
cout<<"Please enter a name or END to terminate:";
cin>>name;
first = 0;
last = size - 1;
middle=0;
friends = false;
while(!friends && first <= last && name != "END");
{
middle = (first + last) / 2;
if (array[middle] == name)
{
friends = true;
cout<<array[middle]<<" is my friend."<<endl;
}
else if (array[middle] > name)
last = middle - 1;
else
last = middle + 1;
}
}
while(name != "END");
I've been reading the book C++ For Everyone and one of the exercises said to write a function string reverse(string str) where the return value is the reverse of str.
Can somebody write some basic code and explain it to me? I've been staring at this question since yesterday and can't figure it out. The furthest I've gotten is having the function return the first letter of str (Which I still don't know how it happened)
This is as far as I got (An hour after posting this question):
string reverse(string str)
{
string word = "";
if (str.length() <= 1)
{
return str;
}
else
{
string str_copy = str;
int n = str_copy.length() - 1;
string last_letter = str_copy.substr(n, 1);
str_copy = str_copy.substr(0, n);
word += reverse(str_copy);
return str_copy;
}
return word;
}
If I enter "Wolf", it returns Wol. Somebody help me out here
If I return word instead of return str_copy then I get a w
If I return last_letter then I get an l
I'll instead explain the recursive algorithm itself. Take the example "input" which should produce "tupni". You can reverse the string recursively by
If the string is empty or a single character, return it unchanged.
Otherwise,
Remove the first character.
Reverse the remaining string.
Add the first character above to the reversed string.
Return the new string.
Try this one
string reverse(string &s)
{
if( s.length() == 0 ) // end condtion to stop recursion
return "";
string last(1,s[s.length()-1]); // create string with last character
string reversed = reverse(s.substr(0,s.length()-1));
return last+reversed; // Make he last character first
}
A recursive function must have the following properties
It must call itself again
It must have a condition when the recursion ends. Otherwise you have a function which
will cause a stack overflow.
This recursive function does basically create a string of the last character and then call itself again with the rest of the string excluding the last character. The real switching happens at the last line where last+reversed is returned. If it would be the other way around nothing would happen.
It is very inefficient but it works to show the concept.
Just to suggest a better way of handling recursion:
String reversal using recursion in C++:
#include <iostream>
#include <string>
using namespace std;
string reverseStringRecursively(string str){
if (str.length() == 1) {
return str;
}else{
return reverseStringRecursively(str.substr(1,str.length())) + str.at(0);
}
}
int main()
{
string str;
cout<<"Enter the string to reverse : ";
cin>>str;
cout<<"The reversed string is : "<<reverseStringRecursively(str);
return 0;
}
I won't write a full-blown algorithm for you, but here's a hint:
How about swapping the two outermost characters, and then apply the same to the characters in the middle?
Oh, and if that book really proposed string reverse(string str) as an appropriate function signature for this, throw it away and buy a good book instead.
Here is my version of a recursive function that reverses the input string:
void reverse(char *s, size_t len)
{
if ( len <= 1 || !s )
{
return;
}
std::swap(s[0], s[len-1]);// swap first and last simbols
s++; // move pointer to the following char
reverse(s, len-2); // shorten len of string
}
Shortest and easiest
class Solution {
public:
string reverseString(string s) {
string str;
if(s != "\0"){
str = reverseString(s.substr(1, s.length()));
str += s.substr(0,1);
}
return str;
}
};
1-line recursive solution:
string RecursiveReverse(string str, string prev = "") {
return (str.length() == 0 ? prev : RecursiveReverse(str.substr(0, str.length()-1), prev += str[str.length()-1]));
}
You call it like this:
cout << RecursiveReverse("String to Reverse");
I know I shouldn't give a solution, but since no one mentioned this easy solution I though I should share it. I think the code literally is the algorithm so there is no need for a pseudo-code.
void c_plusplus_recursive_swap_reverse(std::string::iterator start,
std::string::iterator end)
{
if(start >= end) {
return;
}
std::iter_swap(start, end);
c_plusplus_recursive_swap_reverse(++start, --end);
}
To call it use:
c_plusplus_recursive_swap_reverse(temp.begin(), temp.end());
All existing solutions had way too much code that didn't really do anything, so, here's my take at it:
#include <iostream>
#include <string>
std::string
r(std::string s)
{
if (s.empty())
return s;
return r(s.substr(1)) + s[0];
}
int
main()
{
std::cout << r("testing") << std::endl;
}
P.S. I stumbled upon this question trying to find a C++ way for std::string of what s+1 for a char * in C is; without going the whole route of s.substr(1, s.length()-1), which looks too ugly. Turns out, there's std::string::npos, which means until the end of the string, and it's already the default value for the second argument, so, s.substr(1) is enough (plus, it also looks more efficient and on par with the simple s + 1 in C).
Note, however, that recursion in general doesn't scale as the input grows larger, unless the compiler is able to do what is known as tail-recursion optimisation. (Recursion is rarely relied upon in imperative languages.)
However, in order for the tail recursion optimisation to get activated, it is generally required that, (0), the recursion only happens within the return statement, and that, (1), no further operations are performed with the result of the recursive call back in the parent function.
E.g., in the case above, the + s[0] is logically done by the parent after the child call completes (and it probably would be so even if you go the more uglier s[s.length()-1] + route), so, it might as well prevent most compilers from doing a tail-recursion-optimisation, thus making the function very inefficient on large inputs (if not outright broken due to heap exhaustion).
(For what it's worth, I've tried writing a more tail-recursion-friendly solution (making sure to grow the return result through an argument to the function itself), but disassembly of the resulting binary seems to suggest that it's more involved than that in the imperative languages like C++, see gcc: is there no tail recursion if I return std::string in C++?.)
you can implement your own reverse similar to std::reverse.
template <typename BidirIt>
void reverse(BidirIt first, BidirIt last)
{
if((first == last) || (first == --last))
return;
std::iter_swap(first, last);
reverse(++first, last);
}
I did something like this, it did the reversal in place. I took two variables that traverse the string from two extreme end to the centre of the string and when they overlap or equal to each other then reversal terminates.
Take an example: input string str = "abcd" and call the function as
ReverseString(str,0,str.length()-1);
and increment/decrement the variable pointers recursively.
First the pointers points to 'a' and 'd' and swap them, then they point to 'b' and 'c' and swap them. Eventually i >= j which calls for the base case to be true and hence the recursion terminates. The main take away for this question is to pass input string as reference.
string ReverseString(string& str,int i,int j){
if(str.length() < 1 || str == "" || i >= j){
return "";
}
else{
char temp = str[i];
str[i] = str[j];
str[j] = temp;
ReverseString(str,i+1,j-1);
}
return str;
}
String can be reversed in-place. If we start from smallest possible string i.e. one character string, we don't need to do anything. This is where we stop or return from our recursive call and it becomes our base case.
Next, we have to think of a generic way to swap the smallest string i.e. two characters or more. Simplest logic is to swap the current character str[current_index] with character on the opposite side str[str_length-1 - current_index].
In the end, call the reverse function again for next index.
#include <iostream>
using namespace std;
void reverse_string(std::string& str, int index, int length) {
// Base case: if its a single element, no need to swap
// stop swapping as soon as we reach the mid, hence index*2
// otherwise we will reverse the already reversed string
if( (length - index*2) <= 1 ) {
return;
}
// Reverse logic and recursion:
// swap current and opposite index
std::swap(str[index], str[length-1 - index]);
// do the same for next character (index+1)
reverse_string(str, index+1, length);
}
int main() {
std::string s = "World";
reverse_string(s, 0, s.length());
std::cout << s << endl;
}
There are already some good answer but I want to add my approach with full working Recursive reversing string.
#include <iostream>
#include <string>
using namespace std;
char * reverse_s(char *, char*, int,int);
int main(int argc, char** argv) {
if(argc != 2) {
cout << "\n ERROR! Input String";
cout << "\n\t " << argv[0] << "STRING" << endl;
return 1;
}
char* str = new char[strlen(argv[1])+1];
strcpy(str,argv[1]);
char* rev_str = new char[strlen(str)+1];
cout<<"\n\nFinal Reverse of '" << str << "' is --> "<< reverse_s(str, rev_str, 0, strlen(str)) << endl;
cin.ignore();
delete rev_str, str;
return 0;
}
char* reverse_s(char* str, char* rev_str, int str_index, int rev_index ) {
if(strlen(str) == 1)
return str;
if(str[str_index] == '\0' ) {
rev_str[str_index] = '\0';
return rev_str;
}
str_index += 1;
rev_index -=1;
rev_str = reverse_s(str, rev_str, str_index, rev_index);
if(rev_index >= 0) {
cout << "\n Now the str value is " << str[str_index-1] << " -- Index " << str_in
dex << " Rev Index: " << rev_index;
rev_str[rev_index] = str[str_index-1];
cout << "\nReversed Value: " << rev_str << endl;
}
return rev_str;
}
void reverse(string &s, int &m) {
if (m == s.size()-1)
return;
int going_to = s.size() - 1 - m;
string leader = s.substr(1,going_to);
string rest = s.substr(going_to+1,s.size());
s = leader + s.substr(0,1) + rest;
reverse(s,++m);
}
int main ()
{
string y = "oprah";
int sz = 0;
reverse(y,sz);
cout << y << endl;
return 0;
}
void ClassName::strgRevese(char *str)
{
if (*str=='\0')
return;
else
strgRevese(str+1);
cout <<*str;
}
here is my 3 line string revers
std::string stringRevers(std::string s)
{
if(s.length()<=1)return s;
string word=s.at(s.length()-1)+stringRevers(s.substr(0,s.length()-1));//copy the last one at the beginning and do the same with the rest
return word;
}
The question is to write a recursive function. Here is one approach. Not a neat code, but does what is required.
/* string reversal through recursion */
#include <stdio.h>
#include <string.h>
#define size 1000
char rev(char []);
char new_line[size];
int j = 0;
int i =0;
int main ()
{
char string[]="Game On";
rev(string);
printf("Reversed rev string is %s\n",new_line);
return 0;
}
char rev(char line[])
{
while(line[i]!='\0')
{
i++;
rev(line);
i--;
new_line[j] = line[i];
j++;
return line[i];
}
return line[i];
}
It will reverse Original string recursively
void swap(string &str1, string &str2)
{
string temp = str1;
str1 = str2;
str2 = str1;
}
void ReverseOriginalString(string &str, int p, int sizeOfStr)
{
static int i = 0;
if (p == sizeOfStr)
return;
ReverseOriginalString(str, s + 1, sizeOfStr);
if (i <= p)
swap(&str[i++], &str[p])
}
int main()
{
string st = "Rizwan Haider";
ReverseOriginalString(st, 0, st.length());
std::cout << "Original String is Reversed: " << st << std::endl;
return 0;
}