I'm currently writing a program that uses string functions. I need some advice/hints on how I can display "Hello World" and its length with myStrcat() in main(). I'm new to programming and any support would be greatly appreciated.
My Code:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int myStrlen(char str1[])
{
int i = 0;
for (i=0; str1[i] != '\0'; i++)
str1[i] = '\0';
return i;
}
int myStrcat(char str2[], char str3[])
{
}
int myStrcpy(char str4[], char str5[])
{
int i = 0;
for (i=0; str5[i] != '\0'; i++)
str4[i] = str5[i];
str4[i] = '\0';
return i;
}
int main()
{
const int SIZE = 11;
char s1[SIZE] = "Hello";
char s2[SIZE] = "World";
cout << "s1: " << " " << s1 << endl << endl; ///Should display "Hello"
cout << "The length of s1: " << myStrlen(s1) << endl << endl;
cout << "Doing strcat(s1, s2) " << endl;
myStrcat(s1, s2);
cout << "s1: " << " " << s1 << endl; /// Should display "Hello World"
cout << "The length of s1: " << myStrlen(s1) << endl << endl;
cout << "Doing strcpy(s1, s2) " << endl;
myStrcpy(s1, s2);
cout << "s1: " << " " << s1 << endl; /// Should display "World"
cout << "The length of s1: " << myStrlen(s1) << endl << endl;
My Output:
s1: Hello
The length of s1: 5
Doing strcat(s1, s2)
s1:
The length of s1: 0
Doing strcpy(s1, s2)
s1: World
The length of s1: 5
Line 6 and 7 are suppose to display Hello World and its length (which is 11).
You have a number of not just quite right beginning to each of your functions. Firstly, let's think about the returns for each. myStrlen should return size_t instead of int. C++ designates a size_type for counters, measuring, etc.. The remaining functions should return char* (or nullptr on failure).
Looking at your myStrlen function where you have
for (i=0; str1[i] != '\0'; i++)
str1[i] = '\0';
You are setting every character in str1 to the nul-character because you are applying the loop to the next expression. You should not be worrying about nul-terminating anything within myStrlen -- you are just counting characters. So you can rewrite it as follows:
size_t myStrlen (const char *str)
{
size_t l = 0;
for (; str[l]; l++) {}
return l;
}
Your myStrcpy looks workable, though you should always validate your input parameters are not nullptr before using them -- I leave that to you. Since you have a myStrlen function, you can simply use that along with memcpy to create your myStrcpy function as:
char *myStrcpy (char *dest, const char *src)
{
size_t len = myStrlen(src);
return (char *)memcpy (dest, src, len + 1);
}
(note: traditionally you have source (src) and destination (dest) parameters when copying or concatenating)
For your myStrcat function, you are just using the myStrlen function to find the offset in dest to append src, so you really just need a call to myStrlen and then a call to myStrcpy to copy src to that offset in dest, e.g.
char *myStrcat (char *dest, const char *src)
{
size_t len = myStrlen (dest);
return myStrcpy (dest + len, src);
}
In your main(), if you want a space between "Hello" and "World", then const int SIZE = 11; is one too-low to hold the concatenated string "Hello World" which would require 12-bytes (including the nul-terminating character). Do Not Skimp on buffer size. 128 is plenty small.
Remaining with your main() but updating SIZE = 12; and adding a space between "Hello" and "World" with an additional call to myStrcat, you could do the following:
int main (void)
{
const int SIZE = 12; /* too short by 1 if you add space between */
char s1[SIZE] = "Hello";
char s2[SIZE] = "World";
std::cout << "s1: " << " " << s1 << std::endl << std::endl;
std::cout << "The length of s1: " << myStrlen(s1) << std::endl << std::endl;
std::cout << "Doing strcat(s1, s2) " << std::endl;
myStrcat(s1, " ");
myStrcat(s1, s2);
std::cout << "s1: " << " " << s1 << std::endl;
std::cout << "The length of s1: " << myStrlen(s1) << std::endl << std::endl;
std::cout << "Doing strcpy(s1, s2) " << std::endl;
myStrcpy(s1, s2);
std::cout << "s1: " << " " << s1 << std::endl;
std::cout << "The length of s1: " << myStrlen(s1) << std::endl << std::endl;
}
(note: don't include using namespace std;, it is just bad form in this day and age)
Example Use/Output
$./bin/mystrcpy
s1: Hello
The length of s1: 5
Doing strcat(s1, s2)
s1: Hello World
The length of s1: 11
Doing strcpy(s1, s2)
s1: World
The length of s1: 5
Look things over and let me know if you have further questions.
First you should read Why is “using namespace std;” considered bad practice?
Don't use c style strings if you are starting programming. Use std::string. It's much simpler to use.
#include <iostream>
#include <string>
int myStrlen(const std::string &str) {
return str.length();
}
int myStrcat(std::string &str1, const std::string &str2) {
str1 += str2;
str1.length();
}
int myStrcpy(std::string &str1, const std::string &str2) {
str1 = str2;
return str1.length();
}
int main() {
std::string s1 = "Hello";
std::string s2 = "World";
std::cout << "s1: " << s1 << "\n\n"; ///Should display "Hello"
std::cout << "The length of s1: " << myStrlen(s1) << "\n\n";
std::cout << "Doing strcat(s1, s2) " << '\n';
myStrcat(s1, s2);
std::cout << "s1: " << s1 << '\n'; /// Should display "Hello World"
std::cout << "The length of s1: " << myStrlen(s1) << "\n\n";
std::cout << "Doing strcpy(s1, s2) " << '\n';
myStrcpy(s1, s2);
std::cout << "s1: " << s1 << '\n'; /// Should display "World"
std::cout << "The length of s1: " << myStrlen(s1) << "\n\n";
return 0;
}
Related
This question already has answers here:
How can I convert a std::string to int?
(24 answers)
Closed 2 years ago.
If I have:
string number = "45";
How do I turn "45" into 45 as an integer?
I want to be able to do this:
string number + 20 = 65
You can use the following example from https://en.cppreference.com/w/cpp/string/basic_string/stol:
#include <iostream>
#include <string>
int main()
{
std::string str1 = "45";
std::string str2 = "3.14159";
std::string str3 = "31337 with words";
std::string str4 = "words and 2";
int myint1 = std::stoi(str1);
int myint2 = std::stoi(str2);
int myint3 = std::stoi(str3);
// error: 'std::invalid_argument'
// int myint4 = std::stoi(str4);
std::cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '\n';
std::cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '\n';
std::cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '\n';
//std::cout << "std::stoi(\"" << str4 << "\") is " << myint4 << '\n';
}
I'm attempting to convert a working static String class to a dynamic String class using pointers, but when I implement the pointer it throws a segmentation fault error. Code below:
mystring1.h:
//File: mystring1.h
// Declaration file for user-defined String class.
#ifndef _MYSTRING_H
#define _MYSTRING_H
#include<iostream>
#include <cstring>
using namespace std;
#define MAX_STR_LENGTH 200
class String {
public:
String();
String(const char *s); // a conversion constructor
void append(const String &str);
//deconstructor
~String();
//copy constructor
String (const String & origString);
//assignment operator overload
String operator =(const String &origString);
// Relational operators
bool operator >(const String &str) const;
bool operator <(const String &str) const;
String operator +=(const String &str);
void print(ostream &out) const;
int length() const;
char operator [](int i) const; // subscript operator
private:
char *contents;
int len;
//int capacity;
};
ostream & operator<<(ostream &out, const String & r); // overload ostream operator "<<" - External!
#endif /* not defined _MYSTRING_H */
mystring1.cpp:
//File: mystring1.h
// Implementation file for user-defined String class.
#include "mystring1.h"
String::String()
{
contents[0] = '\0';
len = 0;
}
String::String(const char s[])
{
len = strlen(s);
contents = new char[len + 1];
strcpy(contents, s);
}
void String::append(const String &str)
{
strcat(contents, str.contents);
len += str.len;
}
//deconstructor
String::~String()
{
delete [] contents;
}
//copy constructor
String::String(const String &origString)
{
len = origString.len;
contents = new char[len + 1];
for (int i = 0; i < len; i++)
{
contents[i] = origString.contents[i];
}
}
//assignment operator overload
String String::operator =(const String &origString)
{
if (this != &origString)
{
len = origString.len;
delete [] contents;
contents = new char[len + 1];
for (int i = 0; i < len; i++)
{
contents[i] = origString.contents[i];
}
}
return *this;
}
bool String::operator >(const String &str) const
{
return strcmp(contents, str.contents) > 0;
}
bool String::operator <(const String &str) const
{
return strcmp(contents, str.contents) < 0;
}
String String::operator +=(const String &str)
{
append(str);
return *this;
}
void String::print(ostream &out) const
{
out << contents;
}
int String::length() const
{
return len;
}
char String::operator [](int i) const
{
if (i < 0 || i >= len) {
cerr << "can't access location " << i
<< " of string \"" << contents << "\"" << endl;
return '\0';
}
return contents[i];
}
ostream & operator<<(ostream &out, const String & s) // overload ostream operator "<<" - External!
{
s.print(out);
return out;
}
Assignment 5 Driver:
/**
* cmpsc122 Assignment 5 test file
* File Name: Assign5driver.cpp
*
* Description: This program demonstrates a basic String class that implements
* dynamic allocation and operator overloading.
*
*/
#include <iostream>
#include "mystring1.h"
using namespace std;
/*************************** Main Program **************************/
int main()
{
String str1, str2("dog"); // Using constructor for initial strings
char s1[100], s2[100]; // Some C strings.
// Print out initial strings
cout << "Initial values:" << endl;
cout << "str1 holds \"" << str1 << "\" (length = " << str1.length() << ")" << endl;
cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;
// Inputs some new strings in them
cout << "\nEnter a value for str1 (no spaces): ";
cin >> s1;
str1 = s1;
cout << "\nEnter a value for str2 (no spaces): ";
cin >> s2;
str2 = s2;
cout << "\nAfter assignments..." << endl;
cout << "str1 holds \"" << str1 << "\" (length = " << str1.length() << ")" << endl;
cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;
// Get some elements...
int i;
cout << "\nEnter which element of str1 to display: ";
cin >> i;
cout << "Element #" << i << " of str1 is '" << str1[i] << "'" << endl;
cout << "\nEnter which element of str2 to display: ";
cin >> i;
cout << "Element #" << i << " of str2 is '" << str2[i] << "'" << endl;
// Concate some strings
cout << "\nEnter a value to append to str1 (no spaces): ";
cin >> s1;
// str1.append(s1); // Actually, the cstring is converted to String object here by the constructor
str1 += s1; // same as above
cout << "\nEnter a value to append to str2 (no spaces): ";
cin >> s2;
str2 += s2;
cout << "\nAfter appending..." << endl;
cout << "str1 holds \"" << str1 << "\" (length = " << str1.length() << ")" << endl;
cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;
// Compare strings...
cout << "\nComparing str1 and str2..." << endl;
cout << "\"";
cout<< str1; // test the overloading of ostream operator <<
cout << "\" is ";
if (str1 < str2) { // test the overloading of comparison operator <
cout << "less than";
} else if (str1 > str2) {
cout << "greater than";
} else {
cout << "equal to";
}
cout << " \"";
cout << str2;
cout << "\"" << endl;
cout << "\ntest the = operator, after str1 = str2; "<< endl;
str1 = str2;
cout << "str1 holds \"" << str1 << "\" (length = " << str1.length() << ")" << endl;
cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;
str1 += s1;
cout << "\nAfter str1 = str1 + s1: "<< endl;
cout << "str1 holds \"" << str1 << "\" (length = " << str1.length() << ")" << endl;
cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;
String str3(str2);
cout << "\ntest the copy constructor, after str4(str3);"<< endl;
cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;
cout << "str3 holds \"" << str3 << "\" (length = " << str3.length() << ")" << endl;
cout << "\nafter appending str2 by str1" << endl;
str2 += str1;
cout << "str2 holds \"" << str2 << "\" (length = " << str2.length() << ")" << endl;
cout << "str3 holds \"" << str3 << "\" (length = " << str3.length() << ")" << endl;
cout<< "\nstr3 are not changed. Type any letter to quit." << endl;
char q;
cin >> q;
return 0;
}
Any help would be appreciated, I have tried all that I can and my research into segmentation fault causes isn't doing much to help.
There are several immediately obvious bugs in your implementation:
The default constructor uses uninitialized contents pointer.
The ::append() method does not ensure there is sufficient space in the destination buffer before performing strcat.
The copy constructor and the ::operator=() method do not NUL-terminate the contents buffer.
There are likely more.
You should build your test program with g++ -fsanitize=address ... and fix all the bugs it finds.
You should also build your program with -Wall -Wextra flags, and fix all the warning it produces.
I am passing an string or a char array to a function and swapping them but losing the first char array's value for some reason. Here is my code:
void foo(char* a, char* b){
char* temp;
temp = new char[strlen(a)+1];
strcpy(temp, a);
strcpy(a, b);
strcpy(b, temp);
delete[] temp;
}
So in foo the function gets passed two pointers and the are attempted to be swapped.
Here is the main function. There may be a problem with the passing of the variable, but the compiler did not give me an issue.
int main(){
char a[] = "First";
char b[] = "Last";
std::cout << "A Before: "<< a << "\n";
std::cout << "B Before: " << b << "\n\n";
foo(a, b);
std::cout << "A After: "<< a << "\n";
std::cout << "B After: "<< b << "\n\n";
return 0;
}
The output I am getting is as follows:
A Before: first
B Before: last
A After:
B After: first
Now I have tested the values of the strings while in the function during the strcpy's and turns empty after the final strcpy, which means, or at lest I think, that the problem lies within the pointers to the original variables. It could be a chain reaction type of thing where all of the pointers are pointing to the "a" and it confuses the program.
Any help would be appreciated, also why this is happening would be very useful as well.
Because your string a is longer than b.So strcpy does not work as you expect in line:
strcpy(b, temp);
Tips:
Use strncpy instead of strcpy
Use c++ Strings instead of the c style string.Then you can swap
them with a.swap(b);
The problem is your array sizes happen to be such that you are clobbering your stack; fortunately, for you, the effect is simply to place a null byte in the first character of a, making it an empty string.
#include <iostream>
#include <string.h>
void foo(char* a, char* b){
char* temp = new char[strlen(a)+1];
strcpy(temp, a);
std::cout << "temp = " << temp << " a = " << a << " b = " << b << std::endl;
strcpy(a, b);
std::cout << "temp = " << temp << " a = " << a << " b = " << b << std::endl;
strcpy(b, temp); // this copies 6 bytes to b, which puts a 0 in the first byte of a.
std::cout << "temp = " << temp << " a = " << a << " b = " << b << std::endl;
delete[] temp;
}
int main() {
char a[] = "First";
char b[] = "Last";
std::cout << "a size is " << sizeof(a) << std::endl;
std::cout << "b size is " << sizeof(b) << std::endl;
std::cout << "address of a[0] is " << (void*)&a[0] << std::endl;
std::cout << "address of b[0] is " << (void*)&b[0] << std::endl;
foo(a, b);
std::cout << "A After: "<< a << "\n";
std::cout << "B After: "<< b << "\n\n";
}
http://ideone.com/fDvnnH
a size is 6
b size is 5
address of a[0] is 0xbfec5caa
address of b[0] is 0xbfec5ca5
temp = First a = First b = Last
temp = First a = Last b = Last
temp = First a = b = First
A After:
B After: First
You might want to investigate std::string or look at using std::strncpy
I have following code:
#include <cstring>
#include <boost/functional/hash.hpp>
#include <iostream>
int main(int argc, char **argv)
{
const char *str1 = "teststring";
// copy string
size_t len = strlen(str1);
char *str2 = new char[len+1];
strcpy(str2, str1);
// hash strings
std::cout << "str1: " << str1 << "; " << boost::hash<const char*>()(str1) << std::endl;
std::cout << "str2: " << str2 << "; " << boost::hash<const char*>()(str2) << std::endl;
delete[] str2;
return 0;
}
I always get the same hash for str1 (as expected). But str2 differs - in fact it returns a different hash every time I run the programm.
Can someone explain why?
As Linuxios suggested, it's hashing the pointer value, not the string. I did a quick test with this code:
char str1[] = "teststring";
std::cout << "str1: " << str1 << "; " << boost::hash<const char*>()(str1) << std::endl;
str1[3] = 'x';
std::cout << "str1: " << str1 << "; " << boost::hash<const char*>()(str1) << std::endl;
And here's the output. Note that the string is different but since the pointer is the same the hash matches.
str1: teststring; 158326806782903
str1: tesxstring; 158326806782903
The only change you need to make is to tell boost it's hashing a std::string and it will give you matching hashes. Your underlying data can remain char*.
std::cout << "str1: " << str1 << "; " << boost::hash<std::string>()(str1) << std::endl;
std::cout << "str2: " << str2 << "; " << boost::hash<std::string>()(str2) << std::endl;
Result:
str1: teststring; 10813257313199645213
str2: teststring; 10813257313199645213
If you actually want the hash of the string not the pointer then you can either use the boost::hash_range function or a custom loop using hash_combine and write your own hash function object. boost::hash<std::basic_string<...> > does hashes using hash_range, with has_range in turn using hash_combine.
e.g. something like this:
struct CStringHash : public std::unary_function<char const*, std::size_t> {
std::size_t operator()(char const* v) const {
std::size_t seed = 0;
for (; *v; ++v) {
boost::hash_combine(seed, *v);
}
return seed;
}
};
I'm trying to do a C-style string copy but something is not working right. What am I doing wrong?
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {
char string_a[20]="Good day!";
char string_b[30]="Hi!";
int i=0;
cout << "string a: " << string_a << endl;
cout << "string b: " << string_b << endl;
while (*string_a++ = *string_b++) {
cout << ++i << endl;
}
cout << "string a: " << string_a << endl;
cout << "string b: " << string_b << endl;
return 0;
}
You cannot do:
string_a++
if string_a is defined as an array. That only works for pointers and arrays decay to pointers only in specific circumstances.
If you change:
while (*string_a++ = *string_b++) {
cout << ++i << endl;
}
into:
char *pa = string_a, *pb = string_b; // a "specific circumstance" :-)
while (*pa++ = *pb++) {
cout << ++i << endl;
}
then it will work just fine, outputting:
string a: Good day!
string b: Hi!
1
2
3
string a: Hi!
string b: Hi!