Replacing words in c string - string

I'm having a slight problem with my code here. I just made a small little program to test to put into my actual program. The idea is to replace all the "(star)here(star)" with the string in the add variable. However, when I run the program my final answer is not exactly correct. These are my results:
I_have_a_star_which is super pretty
I_have_a_star_which is super pretty._That_is_great!_I_also_have_a_girlfriendwhich is super pretty
I_have_a_star_which is super pretty._That_is_great!_I_also_have_a_girlfriendwhich is super prett!
Any ideas on what the problem could be would be much appreciated.
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
int main ( )
{
char array[500] = "I_have_a_star_*here*._That_is_great!_I_also_have_a_girlfriend_*here*!",
temp[500],
add[500] = "which is super pretty";
int i=0, j=0;
while(array[i] != '\0')
{
if(array[i] != '*')
{
temp[j]=array[i];
i++;
j++;
}
else
{
strcat(temp,add);
cout << temp << endl;
i+=6;
j+=strlen(add);
}
}
cout << temp << endl;
return 0;
}

The problem is that you're copying characters into the temp array without initializing it or ever NUL terminating it. So when you call strcat or try to print the contents of temp extra garbage on the end may screw things up. Stick memset(temp, 0, sizeof(temp));
before your while loop or change the declaration to temp[500] = "". Alternately, you could add temp[j] = '\0'; just before the call to strcat and just after then loop.

Dude try this...
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
int main ( )
{
char array[500] = "I_have_a_star_*here*._That_is_great!_I_also_have_a_girlfriend_*here*!",
temp[500],
add[500] = "which is super pretty";
int i=0, j=0;
while(array[i] != '\0')
{
if(array[i] != '*')
{
temp[j]=array[i];
i++;
j++;
}
else
{
strcat(temp,add);
i+=6;
j+=strlen(add);
}
}
cout << temp << endl;
return 0;
}

Related

terminate called after throwing an instance of 'std::logic_error' what(): basic_string::_M_construct null not validAborted

this is my code ,the code is written to calculate all possible codes that can be generated from the given string. using recursion.
if input is 1123 it should print all codes as
aabc
kbc
alc
aaw
kw
#include<bits/stdc++.h>
#include <string.h>
using namespace std;
int getCodes(string input, string output[10000]) {
if(input.size()==0)
{
output[0]="";
return 1;
}
int x=input[0]-'0';
char ch='a'+x-1;
int a=getCodes(input.substr(1),output);
for(int i=0;i<a;i++)
{
output[i]=ch+output[i];
}
int mul=10,x2=0;
for(int i=0;i<2;i++)
{
x2=x2+(input[i]-'0')*mul;
mul=mul/10;
}
string output2[1000]={0};
int b=0;
if(x2>10 && x2<=26)
{
char ch2='a'+x2-1;
b=getCodes(input.substr(2),output2);
for(int i=0;i<b;i++)
{
output[a+i]=ch2+output2[i];
}
}
return a+b;
}
int main(){
string input;
cin >> input;
string output[10000];
int count = getCodes(input, output);
for(int i = 0; i < count && i < 10000; i++)
cout << output[i] << endl;
return 0;
}
i'm trying to solve this problem using recursion where ive devided string into a parts where the single char is handle by code and all other are passed for recursion to take care of in another case first two chars are handled by me and remaining are passed to a recursion and finally all are combined

C++ Linked Lists : write access violation error

Here is a simple C++ linked list program . The issue i am facing is when I run my code it takes the first data but then next it shows an exception error.I am running this code on Visual Studio 2017. I have tried a lot but couldn't understand the reason why the code is failing to work.
#include<iostream>
using namespace std;
struct Node {
int data;
Node *next;
}*head = NULL, *temp = NULL , *temp1 = NULL;
Node* Create_New_Node(int);
int Insert(Node *);
Node* Create_New_Node(int a)
{
Node *np = new Node;
np->data = a;
np->next = NULL;
return np;
}
int Insert(Node *np)
{
if (head == NULL) {
head = np;
return 0;
}
temp1 = head;
while(temp1 != NULL) {
temp1 = temp1->next;
}
temp1->next = np;
}
int main()
{
char ch = 'y';
int inf;
while (ch == 'y' || ch == 'Y')
{
system("cls");
cout << "Enter data : " << endl;
cin >> inf;
temp = Create_New_Node(inf);
Insert(temp);
cout << "Press y to continue " << endl;
cin >> ch;
}
system("pause");
return 0;
}
Here is the error output :
'Project2.exe' (Win32): Loaded 'C:\Windows\SysWOW64\ucrtbased.dll'. Symbols loaded.
'Project2.exe' (Win32): Loaded 'C:\Windows\SysWOW64\msvcp140d.dll'. Symbols loaded.
Exception thrown: write access violation.
**temp1** was nullptr.
The program '[10588] Project2.exe' has exited with code 0 (0x0).
Can some one help me with the code since I am new to C++ linked list concept as well as Stack Overflow. Do correct me wherever i go wrong Thanks.
Look at this loop
while(temp1 != NULL) { // <---
temp1 = temp1->next;
}
temp1->next = np;
it ends when temp1 is NULL, then you are trying to access next member for NULL pointer as a result you have segmentation fault.
temp1 can be advanced only if temp1->next is not NULL, so can modify your function as follows
while(temp1->next)
{
temp1 = temp1->next;
}
We don't need to check temp1 if is not NULL because iterating over list starting at head node, and temp1 is always updated to non-NULL value by assignment in above loop.

find method in a stack

I've implemented a method to find a value from a 'Stack'. I just want to know that are there any logical errors or any kind of errors in this code?
Thanks.
bool about::findData(char key)
{
if(top==-1)
cout<<"Stack is Empty"<<endl;
else
{
for(int x=0; x<maxSize-1; x++)
{
if(stackArray[x]==key)
return stackArray[x];
}
}
}
I don't really know what you want to do / ask. From a logical point of view this program will work.
But you got some hops and jumps in there. I will start with a working example and point out the differences.
Note that I won't address the stack logic in itself. It seems like you did start out with a stack like thing, but got driven quite away from it?
You have a (top == -1) query in there, but never ever declared top / assigned a value to it. I assumed that you meant the size of the array (not that this is probably not the best way to calculate the array size, especially as C++ has a vector container anyways).
You iterate over maxSize elements, yet didn't declare maxSize anywhere. This also assumes that your stack is of fixed size and all elements are initiated with a sane value. I am just iterating over the size of the current array right now.
You return the value return stackArray[x];, yet declared your function to have a bool return value - this does no harm in itself, but I went for returning true and false to adhere to the return value.
Try the code online.
#include <iostream>
using namespace std;
int maxSize = 10;
char stackArray[] = {'b', 'a', 'c', 'd'};
//char stackArray[] = {};
bool findData(char key)
{
int top = (sizeof(stackArray)/sizeof(*stackArray));
cout << "Size of array is: " << top << endl;
if(top <= 0)
cout<<"Stack is Empty"<<endl;
else
{
for(int x=0; x<top; x++)
{
if(stackArray[x]==key)
return true;
}
return false;
}
}
int main() {
if(findData('a')) {
cout << "We found the value!" << endl;
} else {
cout << "We didn't find the value!" << endl;
}
}
EDIT
And as I couldn't resist I jump started with an array based stack architecture from here and implemented our beloved findValue within this stack.
#include <iostream>
#include <string>
using namespace std;
class Stack {
private:
int top;
int capacity;
int *storage;
public:
Stack(int capacity) {
if (capacity <= 0)
throw string("Stack's capacity must be positive");
storage = new int[capacity];
this->capacity = capacity;
top = -1;
}
void push(int value) {
if (top == capacity)
throw string("Stack's underlying storage is overflow");
top++;
storage[top] = value;
}
int peek() {
if (top == -1)
throw string("Stack is empty");
return storage[top];
}
void pop() {
if (top == -1)
throw string("Stack is empty");
top--;
}
/* Our findValue function. */
bool findValue(int key) {
/* Now the usage of top makes perfect sense,
the counter variable always contains the amount
of stored elements. */
if (top == -1) {
throw string("Stack is empty");
}
/* We traverse all elements of our storage. */
for (int i = 0; i < top; i++) {
if(storage[i] == key) {
return true;
}
}
return false;
}
bool isEmpty() {
return (top == -1);
}
~Stack() {
delete[] storage;
}
};
int main() {
/* Init the new stack. */
Stack* stack = new Stack(10);
/* Push some elements for more fun. */
stack->push('a');
stack->push('b');
stack->push('c');
stack->push('d');
stack->push('e');
stack->push('f');
/* Show charcode of last pushed element. */
cout << stack->peek() << endl;
/* Find 'e'. */
if (stack->findValue('e')) {
cout << "We found the value" << endl;
}
/* Try and not find 'g'. */
if (!(stack->findValue('g'))) {
cout << "We didn't find the value" << endl;
}
delete stack;
return 0;
}

My functions for a vector don't seem to be working? C++ (adding or deleting an item, displaying a vector)

I'm doing an exercise from my textbook that has me create a program that allows the user to manage a list of favorite games by adding, deleting, or viewing the items in the vector. I made use of functions; my program runs, but the functions don't seem to be doing what they're supposed to. I'm able to input a game name for addGame(), but when I input 4 in the do/while loop, no vector is printed. Likewise, the removeGame() function doesn't seem to be working since it displays no message if I type in a game not in the list.
Which function is at fault for the lack of display? Both or just one (addGame or dispGames)? And why is my removeGame function not working?
Thanks for helping.
// exercises ch 4.cpp : main project file.
#include "stdafx.h"
#include<iostream>
#include<string>
#include<vector>
#include<iterator>
using namespace std;
void addGame(vector<string> faveGames);
void removeGame(vector<string> faveGames);
void dispGames(vector<string> faveGames);
int main(array<System::String ^> ^args)
{
vector<string> faveGames;
int choice;
cout << "Welcome to the Favorite Games List program!\n\n";
do
{
cout << "What would you like to do?\n\n";
cout << "1 - End program. \n 2 - Add new game to list. \n 3 - Remove game from list. \n 4 - Display list. \n";
cout << "Enter the corresponding number of your choice: ";
cin >> choice;
switch (choice)
{
case 1: cout << "Ending program.\n"; break;
case 2: addGame(faveGames) ; break;
case 3: removeGame(faveGames); break;
case 4: dispGames(faveGames); break;
default: "That is not a valid response, please try again.";
}
}
while(choice != 1);
return 0;
}
void addGame(vector<string> faveGames) {
string newFaveGame;
cout << "Enter the name of the game you want to add: ";
cin >> newFaveGame;
faveGames.push_back(newFaveGame);
}
void removeGame(vector<string> faveGames) {
vector<string>::iterator deletedGameIter;
string deletedGame;
cout << "Enter the name of the game you want to delete: ";
cin >> deletedGame;
for(deletedGameIter = faveGames.begin(); deletedGameIter != faveGames.end(); ++deletedGameIter) {
if(deletedGame == *deletedGameIter) {
faveGames.erase(deletedGameIter);
}
else
{
cout << "That game is not on your list.\n";
}
}
}
void dispGames(vector<string> faveGames) {
vector<string>::iterator iter;
for(iter = faveGames.begin(); iter != faveGames.end(); ++iter)
{
cout << *iter << endl;
}
}
Main problem:
You are passing faveGames by value. Any changes to faveGames don't change the variable in main.
You need to pass them by reference if you want the changes to be visible in main:
void addGame(vector<string>& faveGames);
void removeGame(vector<string>& faveGames);
There are other problems in your code that need to be cleaned up too.
Problem
You have
int main(array<System::String ^> ^args)
This is not standard C++ code. Are you using Microsoft Managed C++?
Problem
You have
faveGames.erase(deletedGameIter);
in removeGame. At that point, deletedGameIter is an invalid object. Incrementing it will lead to undefined behavior. You can change the for loop in that function to:
for(deletedGameIter = faveGames.begin();
deletedGameIter != faveGames.end();
++deletedGameIter) {
if(deletedGame == *deletedGameIter) {
faveGames.erase(deletedGameIter);
return
}
}
if you don't expect to see the game multiple times in the your list. If you expect to see it multiple times, you can use:
for(deletedGameIter = faveGames.begin();
deletedGameIter != faveGames.end(); ) {
if(deletedGame == *deletedGameIter) {
deletedGameIter = faveGames.erase(deletedGameIter);
}
else {
++deletedGameIter;
}
}

Overloading "*" Operator for custom SmartPointer

I am trying to directly access integer from a pointer class, by overloading * operator, but it seems VC++ 10 is not allowing it. Kindly help:
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
int MAX7 = 10;
struct node{
int value;
node *next;
};
struct node *head = NULL;
struct node *current = NULL;
int count = 0;
class SmartPointer{
public:
SmartPointer(){
}
int push(int i){
if(count == MAX7) return 0;
if(head == NULL){
head = new node();
current = head;
head -> next = NULL;
head -> value = i;
count = 1;
}
else{
struct node *ptr = head;
while(ptr->next != NULL) ptr = ptr->next;
ptr->next = new node;
ptr = ptr->next;
ptr->next = NULL;
ptr->value = i;
count++;
}
return 1;
}
void Display(){
node *ptr = head;
while(ptr != NULL){
cout << ptr->value << "(" << ptr << ")";
if( ptr == current )
cout << "*";
cout << ", ";
ptr = ptr->next;
}
}
int operator *(){
if(current == NULL) return -1;
struct node *ptr = current;
return ptr->value;
}
};
int main(){
SmartPointer *sp;
sp = new SmartPointer();
sp->push(99);
for(int i=100; i<120; i++){
if(sp->push(i))
cout << "\nPushing ("<<i<<"): Successful!";
else
cout << "\nPushing ("<<i<<"): Failed!";
}
cout << "\n";
sp->Display();
int i = *sp;
getch();
return 0;
}
Error#
1>test7.cpp(71): error C2440: 'initializing' : cannot convert from 'SmartPointer' to 'int'
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
sp is not a smart pointer - it's a plain old dumb pointer to SmartPointer class. *sp uses built-in dereference operator, producing an lvalue of SmartPointer type. It does not call SmartPointer::operator*() - for that, you need to write **sp (two stars).
It's not at all clear why you want to allocate SmartPointer instance on the heap. That's an unusual thing to want to do (also too, you leak it). I'm pretty sure you would be better off with
SmartPointer sp;
sp.push(99);
and so on.
short answer:
int i = **sp;
You should not allocate objects with new. Your code looks like java. In C++, you must delete everything you allocate with new. In C++ you can write:
SmartPointer sp;
sp.push(99);
int i = *sp;

Resources