I would like to reverse a c-style string and came up with the following code.
Play with the code
#include <iostream>
void reverse_c_str(char *c)
{
char *new_c = c;
for (; *new_c; ++new_c){} // find '\0'
--new_c; // new_c is now at the actual last char, which is 'g'
while (c < new_c) // swap chars
{
char tmp = *c;
*c = *new_c; // crash
*new_c = tmp;
--new_c;
++c;
}
}
int main()
{
char *c = "my string";
reverse_c_str(c);
std::cout << c << '\n';
}
Unfortunately, my code has an error, which I marked with // crash. Why does this line crash?
"my string" is a string literal, it is const.
It can be cast to a non-const char * for reasons of compatibility with C, but modifying a constant invokes undefined behavior. In some cases the OS will prevent it (as when it's stored in a read-only section), which is probably what you're observing.
Make a copy of the string in automatic storage, then you'll be able to modify it:
int main()
{
char c[] { "my string" };
reverse_c_str(c);
std::cout << c << '\n';
}
And of course there is a templated soultion:
#include <cstring>
template<std::size_t N>
void reverse_c_str(char (&str)[N]) {
std::size_t len = N-1;
for (std::size_t i = 0; i < len/2; ++i) {
str[i] ^= str[len-i-1];
str[len-i-1] ^= str[i];
str[i] ^= str[len-i-1];
}
}
int main() {
char c[] {"123"};
reverse_c_str(c);
char c2[] {""};
reverse_c_str(c2);
char c3[] {"4321"};
reverse_c_str(c3);
return 0;
}
Use std::swap and std::strlen. I made example for you here.
#include <iostream>
#include <cstring>
void reverse_c_str(char *c) {
int length = std::strlen(c);
for (int i = 0; i < length / 2; i++)
std::swap(c[i], c[length - i - 1]);
}
int main()
{
char c[] { "my string" };
reverse_c_str(c);
std::cout<<c << std::endl;
return 0;
}
Output:
gnirts ym
Another one version of function reverse_c_str
void reverse_c_str(char *c) {
if(*c) {
for(auto begin = c, end = c + std::strlen(c) - 1;
begin < end; ++begin, --end
) {
std::swap(*begin, *end);
}
}
}
Related
Here is my code
int main(int argc, char *argv[]) {
char const *strings[10] = {"dhh", "aci", "cdh"};
join_def(strings, 'l');
return EXIT_SUCCESS;
}
// part 1 read lines
void join_def(char const **strings, char delim) {
char *t = new char[100];
//int length = 0;
t[0] = '\0';
int x = sizeof(strings);
std::cout << delim << std::endl;
for (int i = 0; i < x; i++) {
int size = 0;
while(strings[i][size]!='\0'){
size++;
std::cout << strings[i][size] << std::endl;
}
}
}
I have spent hours now I just can't get to concatenate it
For this task, I cannot use cstring or anything other than iostream so please don't suggest.
The output needs to be a c-string = "dhhlacilcdh"
First, you cannot determine the number of elements in an array passed to a function, as that array will decay to a simple pointer. So, your sizeof(strings) expression will evaluate (at compile time) to the (fixed) size, in bytes, of a pointer. For the function to be 'aware' of how many elements there are in an array, it needs to be explicitly told (by way of an extra argument).
Second, you have your i' and size indexes the wrong way round in the std::cout << strings[i][size] << std::endl; line and, further, you increment size before printing the relevant character, whereas it should be incremented after you've printed it.
The code below also does the actual concatenation of the strings, and the modified join_def function now returns a pointer to that result (which must be freed when you're finished with it);
#include <iostream>
char* join_def(char const** strings, char delim, int x)
{
char* t = new char[100];
int length = 0;
t[0] = '\0';
//int x = sizeof(strings);
std::cout << delim << std::endl;
for (int i = 0; i < x; i++) {
int size = 0;
while (strings[i][size] != '\0') {
std::cout << strings[i][size] << std::endl;
t[length++] = strings[i][size]; // Append this character
size++;
}
t[length++] = delim; // Append delimiter
}
t[length] = '\0'; // Append nul-terminator
return t;
}
int main()
{
char const* strings[10] = { "dhh", "aci", "cdh" };
char* result = join_def(strings, 'l', 3);
std::cout << result << std::endl;
free(result);
return 0;
}
Note, also, that I have moved the join_def function code to before the main (which calls it). If you don't do this, then will at least have to provide a (forward) declaration of that function before main (just a char* join_def(char const** strings, char delim, int x); on its own will do).
Feel free to ask for further clarification and/or explanation.
I'm not exactly sure what you're trying to do, but maybe this helps?
#include <iostream>
// part 1 read lines
void join_def(char const **strings, char delim)
{
char *t = new char[100];
//int length = 0;
t[0] = '\0';
int x = 0;
for (int i = 0; strings[i] != nullptr; i++)
x += sizeof(strings[i]) - 1;
std::cout << delim << std::endl;
for (int i = 0; strings[i] != nullptr; i++)
{
int size = 0;
while (strings[i][size] != '\0')
{
size++;
std::cout << strings[i][size] << std::endl;
}
}
}
int main(int argc, char *argv[])
{
char const *strings[] = {"dhh", "aci", "cdh", nullptr};
join_def(strings, 'l');
return EXIT_SUCCESS;
}
this is what you are looking for?
look that I remove all the std::endl because it like '\n'
also i moved your size++ after the std::cout
#include <iostream>
// part 1 read lines
void join_def(char const **strings, char delim,int length) {
char *t = new char[100];
//int length = 0;
t[0] = '\0';
int x = length;
for (int i = 0; i < x; i++) {
int size = 0;
while(strings[i][size]!='\0'){
std::cout << strings[i][size]; //<--print befure increment size
size++;
}
std::cout << delim;
}
}
int main(int argc, char *argv[]) {
char const *strings[] = {"dhh", "aci", "cdh"};
join_def(strings,'|',3); //<- need to send the length of the char* array
return EXIT_SUCCESS;
}
Write and test your own function char * funct (char * str, int x) inverting (except for the character at position n) the string str and returning the modified str as the result. The use of the function funct could be:
This is main:
#include <iostream>
#include <cstring>
using namespace std;
char* funct(char *str, int x);
int main() {
char str1 [] = "Hello cpp";
cout << str1 << endl; // Hello cpp
cout << funct (str, 1) << endl; // pepC ollH // the character at position 1 ('e') stays in place
return 0;
}
This is my function:
char* funct(char *str, int x) {
int counter = 0;
do {
counter++;
str++;
} while (*str);
str--;
char *wskTmp = str;
for (int i = 0; i < counter ; i++) {
*wskTmp = *str;
str--;
wskTmp++;
}
*wskTmp = '\0';
wskTmp = wskTmp - counter;
for (int i = 0; i < counter - x -1; i++) {
wskTmp++;
}
char tmp;
for (int i = 0; i < counter-3; i++) {
tmp = *(wskTmp - 1);
*(wskTmp - 1) = *wskTmp;
*wskTmp = tmp;
wskTmp--;
}
return str;
}
Output:
Hello Cpp
Hello CppepC ollH
It should be:
Hello Cpp
pepC ollH
Why it gives me Hello Cp before "pepC ollH"?
Your code is very confusing and is a very roundabout way of accomplishing this task, so I restructured it a bit:
#include <cstring>
#include <iostream>
using namespace std;
char *funct(char *str, int x) {
// keep track of the original start
char *origStr = str;
// iterate through the string to find the end
do {
str++;
} while (*str);
// decrease the string so it's on the last byte, not the nullbyte
str--;
// create a start and end
char *start = origStr;
char *end = str;
if (start - origStr == x) {
start ++;
}
if (end - origStr == x) {
end--;
}
// if start >= end then we've finished
while (start < end) {
// swap values at start and end
char temp = *start;
*start = *end;
*end = temp;
// move the pointers closer to each other
start++;
end--;
// skip the index x
if (start - origStr == x) {
start++;
}
// skip the index x
if (end - origStr == x) {
end--;
}
}
// make sure to return the actual start
return origStr;
}
int main() {
char str1[] = "Hello cpp";
cout << str1 << endl; // Hello cpp
cout << funct(str1, 1) << endl; // pepC ollH // the character at position 1
// ('e') stays in place
return 0;
}
I have not found good answer for my question so i decided to ask my own question.
I need to read input from console with my own function in following format:
a RL
b RLRL
c RLLL
...
in general:
(character)(space)(character sequence or empty)(new line character)
I want to read it into char arrays one by one. I mean I want to read one line, do something with data, then read second one and so on...
Problem is that I do not know number of lines and I do not know how to stop it.
Checking if it is new line character (ASCII 10) does not work because it is in every single line.
There is my code:
#include <iostream>
#include <cstdio>
using namespace std;
int input_size;
char c;
bool finish;
inline int read(char* v, char* arr) {
int counter = 0;
c = getchar();
*v = c; //Pobranie wartości węzła
input_size++;
char* tmp = arr;
c = getchar();
c = getchar();
while (c != 32 && c != 10) {
input_size++;
*tmp++ = c;
c = getchar();
counter++;
}
if(c == 10)
finish = false;
return counter;
}
void show(char* t, int c) {
char* tmp = t;
for(int i = 0; i < c; i++) {
cout << *tmp;
tmp++;
}
delete[] tmp;
}
int main()
{
finish = true;
char* a = new char[1];
char* b = new char[64];
while(finish) {
int c = read(a, b);
cout << "char: " << *a << endl;
cout << "char sequence: ";
show(b,c);
cout << endl;
}
return 0;
}
I get the following output: olleh�hello but can't figure out where I'm going wrong!
int main()
{
char hello[6] = "hello";
char temp[6];
unsigned int t = 0;
for(int i=strlen(hello)-1;i>=0;i--)
{
if(t<strlen(hello))
{
temp[t] = hello[i];
t++;
}
}
cout << temp;
return 0;
}
You need a null terminator at the end of the string:
int main()
{
char hello[6] = "hello";
char temp[6];
unsigned int t = 0;
for(int i=strlen(hello)-1;i>=0;i--)
{
if(t<strlen(hello))
{
temp[t] = hello[i];
t++;
}
}
temp[t] = '\0';
cout << temp;
return 0;
}
you tagged the question as [C++], so here's C++ way to reverse string:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string hello = "hello";
std::reverse(hello.begin(), hello.end());
std::cout << hello << std::endl;
}
it's difficult to make any mistake here
You aren't terminating temp with a null (\0), so temp isn't a valid string and cout doesn't know quite what to do with it. Your problem will go away if you add:
temp[5] = 0;
after the for loop.
I came up with this, since other examples provided on stackoverflow were in C#
string number_fmt(ulong n)
{
// cout << "(" << n << ")" << endl;
char s[128];
sprintf(s, "%lu", n);
string r(s);
reverse(r.begin(), r.end());
int space_inserted = 0;
size_t how_many_spaces = r.length() / 3;
if(r.length() % 3 != 0)
how_many_spaces += 1;
for(int i = 1; i < how_many_spaces; ++i)
{
r.insert(3 * i + space_inserted, " ");
space_inserted += 1;
}
reverse(r.begin(), r.end());
return r;
}
Do you know any better solution ?
I don't know about "better", but this version uses std::locale, etc.
#include <iostream>
#include <locale>
#include <sstream>
template<class Char>
class MyFacet : public std::numpunct<Char> {
public:
std::string do_grouping() const { return "\3"; }
Char do_thousands_sep() const { return ' '; }
};
std::string number_fmt(unsigned long n)
{
std::ostringstream oss;
oss.imbue(std::locale(oss.getloc(), new MyFacet<char>));
oss << n;
return oss.str();
}
int main() {
std::cout << number_fmt(123456789) << "\n";
}
EDIT: Of course, if your final goal is to print the values on an ostream, you can skip storing them in a string altogether.
#include <iostream>
#include <locale>
#include <sstream>
#include <cwchar>
template <class Char>
class MyFacet : public std::numpunct<Char> {
public:
std::string do_grouping() const { return "\3"; }
Char do_thousands_sep() const { return ' '; }
};
int main(int ac, char **av) {
using std::locale;
using std::cout;
// Show how it works to start with
cout << 123456789 << "\n";
// Switch it to spacey mode
locale oldLoc =
cout.imbue(locale(cout.getloc(), new MyFacet<char>));
// How does it work now?
cout << 456789123 << "\n";
// You probably want to clean up after yourself
cout.imbue(oldLoc);
// Does it still work?
cout << 789123456 << "\n";
}
This is already done by the locale.
The default local is "C" which does no formatting. But you can set it to your current language-specific local (as defined by your computer's setting by setting the current local as the first line of main).
int main()
{
std::locale::global(std::locale("")); // Set the default local of the machine
// Will be used by all streams.
// The "" will find the machine specific local
// and use that instead of the "C" locale
// Note: The C local should only be used for programmers.
// Alternatively you can imbue particular stream with the local
// To achieve a localized effect
// std::cout.imbue(std::locale(""));
// Now all you do is print the number.
std::cout << "123456789\n"; // This will print the number according to your local
} // For me US-en this is 123,456,789
// Your may very.
If you want to do something explicitly then you can set a facet in the local for printing numbers.
#include <iostream>
#include <locale>
#include <string>
template<typename CharT>
struct Sep : public std::numpunct<CharT>
{
virtual std::string do_grouping() const {return "\003";}
virtual CharT do_thousands_sep() const {return ':';}
};
int main()
{
std::cout.imbue(std::locale(std::cout.getloc(), new Sep <char>()));
std::cout << 123456789 << "\n"; // this prints 123:456:789
}
This one is different, but better is subjective. I think it's very succinct and clear what it's doing though:
string number_fmt(unsigned long long n, char sep = ',') {
stringstream fmt;
fmt << n;
string s = fmt.str();
s.reserve(s.length() + s.length() / 3);
// loop until the end of the string and use j to keep track of every
// third loop starting taking into account the leading x digits (this probably
// can be rewritten in terms of just i, but it seems more clear when you use
// a seperate variable)
for (int i = 0, j = 3 - s.length() % 3; i < s.length(); ++i, ++j)
if (i != 0 && j % 3 == 0)
s.insert(i++, 1, sep);
return s;
}
Using it like
cout << number_fmt(43615091387465) << endl;
prints
43,615,091,387,465
Admittedly, if one wanted to have the most possible efficient version and didn't mind specializing it for the case at hand, using a local char buffer can help a lot.
#include <iostream>
#include <string>
std::string format(unsigned long long i) {
char buffer[128]; // can be adapted more tightly with std::numeric_limits
char* p = buffer + 128;
*(--p) = '\0';
unsigned char count = 0;
while (i != 0) {
*(--p) = '0' + (i % 10);
i /= 10;
if (++count == 3) { count = 0; *(--p) = ' '; }
}
return p;
}
int main() {
std::cout << format(1234567890) << '\n';
}
In action at ideone:
1 234 567 890
(Key point: for number printing, go backward)
Not very optimal but small
QString str = QString::number(d);
for (int i = 3; str.size() > i; i += 4)
str.insert(str.size() - i, ' ');
If "better" means more efficient, you should:
use reserve on the output string (you know its size...)
avoid the insert in the middle of the string, because you have to copy a big part of the string each time you do that.
I would say something like this (untested):
std::string number_fmt (ulong n)
{
std::ostringstream buff;
buff << n;
std::string without_spaces = buff.str ();
std::string with_spaces;
with_spaces.reserve ((without_spaces.size () * 4) / 3);
std::size_t nb_inserted = 0;
for (auto it = without_spaces.rbegin (); it != without_spaces.rend (); ++it)
{
if (nb_inserted % 3 == 0 && nb_inserted != 0)
{
with_spaces.push_back (' ');
}
++ nb_inserted;
with_spaces.push_back (*it);
}
std::reverse (with_spaces.begin (), with_spaces.end ());
return with_spaces;
}