I am struggling with a project in which you read lines from a text file, put the said strings into cstrings, and reverse them. I am not allowed to use the actual reverse function.
#include <iostream>
#include <cstring>
#include <string>
#include <fstream>
usingnamespace std;
void readFile(ifstream &infile, string s[], int &size);
void reverse(char* str);
constint MAX = 20;
string strArr[MAX];
int size;
int main() {
ifstream infile("in.txt");
readFile(infile,strArr,size);
char* cstr = newchar [MAX+1];
for (int j = 0; j < size; ++j) {
cout<<strArr[j]<<endl;
}
cout<<"Before cstring"<<endl;
for (int i = 0; i <size; ++i) {
std::strcpy (cstr, strArr[i].c_str());
for (int j = 0; j < 11; ++j) {
cout<<cstr[j];
}
cout<<endl;
//cout<<strArr[i]<<endl;
}
cout<<endl;
cout<<"After cstring"<<endl;
reverse(cstr);
//Here is where I have one question as well, is this the right way to print?
for (int k = 0; k < size; ++k) {
for (int i = 0; i < size; ++i) {
cout<<cstr[k]<<cstr[i];
}
cout<<endl;
}
cout<<endl;
cout<<"After reverse"<<endl;
}
readFile
1 2 3 4 5 6 7 8 9 10 11 12
void readFile(ifstream &infile, string s[], int &size)
{
if (!infile) {
std::cout << "\n Error message\n";
}
for (int i = 0; i < 3; ++i)
{
infile>>s[i];
size++;
}
}
void reverse(char* cstr)
{
// If str is NULL, do nothing
if (cstr == NULL)
return;
// assign end character to pointer
char* pointer_end = cstr + (strlen(cstr) - 1);
// start swapping characters from both ends of the string
while (pointer_end > cstr)
{
char ch = *cstr;
*cstr = *pointer_end;
*pointer_end = ch;
//increment the starting position, and decrement the ending position
++cstr, --pointer_end;
}
}
The result printed is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
programming
is
fun
Before cstring
programming
is gramming
fun ramming
After cstring
nnnunf
unuuuf
fnfuff
After reverse
My big questions are as follows
1. Is that the right way to reverse a cstring?
2. Is that the right way to print said cstring?
3. Why is the "ramming" part being printed at the end every time?
If you must use C-strings, then use C-strings for everything. You're probably confusing yourself by using C++ strings and C-strings, they are quite different.
Also unless it is absolutely for the assignment necessary avoid dynamic memory, statically allocate the array sizes.
Also stop using global variables, pass the variables to and from your functions as required.