Here is my declaration in question, I even use include guards:
Edit: I'm including the entire header if this will help answer any additional
questions one might have.
#ifndef STRING_H
#define STRING_H
#include<iostream>
class String
{
public:
String(const char * s = "");
String(const String & s);
String operator = (const String & s);
char & operator [] (int index);
int size();
String reverse();
int indexOf(char c);
int indexOf(String pattern);
bool operator == (String s);
bool operator != (String s);
bool operator > (String s);
bool operator < (String s);
bool operator >= (String s);
bool operator <= (String s);
String operator + (String s);
String operator += (String s);
void print(std::ostream & out);
void read(std::istream & in);
static int strLen(const String &s);
static String strCpy(const String &s, int length);
static String strDup(const String &s);
static bool strCmp(const String &s, const String &t);
~String();
private:
bool inBounds(int i)
{
return i >= 0 && i < len;
}
char * buf;
int len;
};
#endif
And here is my definition:(starting form line 183)
String String::operator = (const String & s)
{
String t(s);
return t;
}
And I keep getting this error:
>c:\users\omive_000\documents\visual studio 2013\projects\string\string\string.h(183): error C2084: function 'String String::operator =(const String &)' already has a body
1> c:\users\omive_000\documents\visual studio 2013\projects\string\string\string.h(11) : see previous definition of '='
can anyone offer me an explanation as to why this error occurs?
Definitions normally don't belong into header files.
You can declare and define your function inline, inside your include guards
You can use a cpp file
That said, your code looks fishy. It does not do what it seems to do. There is no assignment to this or it's variables happening. But that's a bug and not a compiler error.
Related
I am doing a online code challenge that asks to write a anagram checker program. So i made the following the program and for some weird reason it's not passing all the test cases. I wrote a main function on my own and tried to test it myself and it seems to work fine.
#include<iostream>
using namespace std;
bool anagrams(string str1, string str2);
int main(){
string str1="abcd";
string str2="dcba";
cout<<anagrams(str1,str2)<<endl;
cin.get();
return 0;
}
bool anagrams(string str1, string str2){
if(str1.length()!=str2.length()) return false;
for(int i=0;i <str1.length(); i++){
for(int j=0;j<str2.length();j++){
if(str1[i]==str2[j]){
str1[i]='*';
break;
}
}
}
for(int i=0;i<str1.length();i++){
if(str1[i]!='*') return false;
}
return true;
}
It looks like your code checks if the characters in str1 exist in str2.
For example, if str1="abca" and str2="abcd" they are clearly not anagrams.
However won't it turn str1 into "****" since it will match the last a in str1 to the first a in str2 (twice).
Okay, so the program wouldn't work with inputs such as
abcc
abcd
So a quick fix would be marking the character from str2 with * as you iterate through each character in str1.
#include<iostream>
using namespace std;
bool anagrams(string str1, string str2);
int main(){
string str1="abcc";
string str2="dcba";
cout<<anagrams(str1,str2)<<endl;
cin.get();
return 0;
}
bool anagrams(string str1, string str2){
if(str1.length()!=str2.length()) return false;
for(int i=0;i <str1.length(); i++){
for(int j=0;j<str2.length();j++){
if(str1[i]==str2[j]){
str2[j]='*';
break;
}
}
}
for(int i=0;i<str2.length();i++){
if(str2[i]!='*') return false;
}
return true;
}
There are better algorithms out there for anagram checkers, such as sorting and using a hashable.
package com.datastructures.programs;
public class Anagram {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = "abcc";
String s2 = "abcd";
System.out.println(Anagram.isAnagram(s1, s2));
}
private static boolean isAnagram(String s1, String s2) {
// TODO Auto-generated method stub
int[] temp = new int[256];
boolean isAnagram = true;
if (s1.length() != s2.length()) {
return false;
}
for (char s : s1.toCharArray()) {
int index = (int) s;
temp[index]++;
}
for (char s : s2.toCharArray()) {
int index = (int) s;
temp[index]--;
}
for (int i = 0; i < 256; i++) {
if (temp[i] != 0) {
return false;
}
}
return true;
}
}
I'm currently working on a project to convert from postfix to infix using a stack implemented through a linked list. I'm trying to take in a line and then pushing each character onto a stack however I keep getting the error.
Error: invalid user-defined conversion from ‘char’ to ‘const stack_element& {aka const std::basic_string&}’
Here is my code:
#include "stack.h"
string convert(string expression)
{
stack c;
string post = " ";
for (int i =0; i<expression.length(); i++)
{
c.push(expression[i]);
}
}
int main()
{
string expression;
cout<<" Enter a Post Fix expression: ";
getline(cin,expression);
return 0;
}
and here is the push function written in another .cpp file
void stack::push(const stack_element & item)
{
cout<<"Inside push \n";
stack_node *p = new stack_node;
p->data = item;
p->next = s_top;
s_top = p;
}
do not use const as parameter in your push function
void stack::push(stack_element & item)
Change void stack::push(const stack_element & item)
to void stack::push(cons char& item) , As in your case , you are trying to create stac of characters . If you want generic use templates.
void extractWord (string& str)
I have to write a function that extracts the word between ‘*’.
For example, using the three test cases below:
string s = "This is to be *reversed*"
string s1 ="*Reversed* starts here";
string s2 = "This is *in* the middle";
and after each function call,
s=reversed, s1=Reversed, s2=in
So i figured out...
void extractWord (string& str)
{
char target= '*';
int idx1=0;
while (str[idx1] != target)
idx1=idx1+1;
int idx2=idx1+1;
while (str[idx2] != target)
idx2=idx2+1;
for(int i=0;i<sizeof(str);i++)
{
if ((i>idx1)&&(i<idx2))
cout<<str[i];
}
}
int main()
{
string s="This is to be *reversed*";
string s1 = "*Reversed* starts here";
string s2= "This is *in* the middle";
extractWord(s);
cout<<endl;
extractWord(s1);
cout<<endl;
extractWord(s2);
cout<<endl;
}
but how do I change the value of s into the output of this function?
I have modified your code a bit. I hope this solves your problem:
//#include "stdafx.h"
#include < string >
#include < iostream >
using namespace std;
void extractWord (string& str)
{
char target= '*';
int idx1=0;
while (str[idx1] != target)
idx1=idx1+1;
int idx2=idx1+1;
while (str[idx2] != target)
idx2=idx2+1;
str=str.substr(idx1+1,idx2-idx1-1); //changed
}
int main()
{
string s="This is to be *reversed*";
string s1 = "*Reversed* starts here";
string s2= "This is *in* the middle";
extractWord(s);
cout<<s<<endl; //changed
extractWord(s1);
cout<<s1<<endl; //changed
extractWord(s2);
cout<<s2<<endl; //changed
system("PAUSE");
return 0;
}
Now, every time you call void extractWord (string& str) it replaces string with only word between *'s.
I've used std::string::substr function. > http://www.cplusplus.com/reference/string/string/substr/
Other option is to make function that returns word between *'s.
//#include "stdafx.h"
#include < string >
#include < iostream >
using namespace std;
string extractWord (string& str)
{
char target= '*';
int idx1=0;
while (str[idx1] != target)
idx1=idx1+1;
int idx2=idx1+1;
while (str[idx2] != target)
idx2=idx2+1;
return str.substr(idx1+1,idx2-idx1-1);
}
int main()
{
string s="This is to be *reversed*";
string s1 = "*Reversed* starts here";
string s2= "This is *in* the middle";
string res;
res=extractWord(s);
cout<<res<<endl;
res=extractWord(s1);
cout<<res<<endl;
res=extractWord(s2);
cout<<res<<endl;
system("PAUSE");
return 0;
}
However, note that it doesn't work if your string do not contain two *'s or it has more than one word that has to be extracted. I hope this helped you.
I want to write myself a function similar to PHP's str_repeat. I want this function to add specified amount of characters at the end of string.
This is a code that does not work (string argument 2 expected!)
void chrrepeat(const char &ch, string &target, const int &count) {
for(int i=0; i<count; i++)
strcat(target, ch);
}
I don't exactly know what language is that (C++?), but you seem to be passing a char to strcat() instead of a null-terminated string. It's a subtle difference, but strcat will happily access further invalid memory positions until a null byte is found.
Instead of using strcat, which is inefficient because it must always search up to the end of the string, you can make a custom function just for this.
Here's my implementation in C:
void chrrepeat(const char ch, char *target, int repeat) {
if (repeat == 0) {
*target = '\0';
return;
}
for (; *target; target++);
while (repeat--)
*target++ = ch;
*target = '\0';
}
I made it return an empty string for the case that repeat == 0 because that's how it works in PHP, according to the online manual.
This code assumes that the target string holds enough space for the repetition to take place. The function's signature should be pretty self explanatory, but here's some sample code that uses it:
int main(void) {
char test[32] = "Hello, world";
chrrepeat('!', test, 7);
printf("%s\n", test);
return 0;
}
This prints:
Hello, world!!!!!!!
Convert char to string.
void chrrepeat(char ch, string &target, const int count) {
string help = "x"; // x will be replaced
help[0] = ch;
for(int i=0; i<count; i++)
strcat(target, help);
}
how to convert integer into string pointer in visual c++?
Use stringstream
#include <sstream>
stringstream ss;
ss << i;
string s = ss.str();
If you using CString, then you can use Format() method like this:
int val = 489;
CString s;
s.Format("%d", val);
search for atoi / itoa in your favorite documentation. Or try Boost (www.boost.org - library Conversion, lexical_cast).
Both ways are portable across different compilers.
There is a very easy method
int i=4;
String ^ s = Convert::ToString(i);
If you want a textual representation of the pointer address use sprintf.
If you want to treat the numeric value as a pointer to a string use casting like so:
int intValue = ...;
char * charPtr = (char*)intValue;
Take any C and C++ textbook. This simple C code should work in Visual C++ and others C++ compilels and convert 489 into "489":
char result[100];
int num = 489;
sprintf(result, "%d", num);
basic C++
char text[100];
int num=123;
itoa(num,text,10);
This is how I did it in my homework since we were only allowed to use some predetermined libraries. I'm pretty sure it's not considered a "best practice" though ;)
string int2string(int integer) {
string str;
int division = integer;
while (division > 0) {
str = char('0' + (division % 10)) + str;
division = division / 10;
}
return str;
}
I think the easiest one would be:
int i;
String s=i.toString();
// It is about Visual C++
You got homework? a generic one, tested if g++, http://effocore.googlecode.com/svn/trunk/devel/effo/codebase/addons/inl/include/impl/algo_impl.h
:
#ifdef __cplusplus
static inline char *int2a_put(uintptr_t i, char *s)
{
do {
*s++ = '0' + i % 10;
i /= 10;
} while (i);
return s;
}
static inline void int2a_reverse(char *head, char *tail)
{
for (*tail = '\0'; --tail > head; ++head) {
/* exchange */
(*head) ^= (*tail);
(*tail) ^= (*head);
(*head) ^= (*tail);
}
}
template<typename t>
static inline const char *int2a(t i, char *s)
{
char *p;
char *ret = s;
bool f = false;
p = s;
if (i < 0) {
*p++ = '-';
++ s;
/*
* In limits.h, INT_MAX was defined as
* maximum values a `signed int' can hold.
* and LONG_MAX was defined as maximum values
* a `signed long int' can hold.
*/
switch (sizeof(t)) {
case 8:
{
/*
* Inject \p a to prevent from complaint
* of compiler.
*/
ef64_t a = (ef64_t)i;
if (-LLONG_MAX > a) {
i = (t)LLONG_MAX;
f = true;
}
}
break;
case 4:
case 2:
case 1:
{
/*
* Inject \p a to prevent from complaint
* of compiler.
*/
int a = (int)i;
if (-INT_MAX > a) {
i = (t)INT_MAX;
f = true;
}
}
break;
default:
break;
}
if (!f) {
i = -i;
}
}
p = int2a_put((uintptr_t)i, p);
if (f) {
++ *s;
}
int2a_reverse(s, p);
return ret;
}
/*
* No "static" otherwise g++ complains
* "explicit template specialization cannot have a storage class"
*/
template<>
/*static*/ inline
const char *int2a<uintptr_t>(uintptr_t i, char *s)
{
char *p = int2a_put(i, s);
int2a_reverse(s, p);
return s;
}
#else