C++ string not printed - c++

I have the next code:
void addContent ( const std::string& message ) {
std::string newMessage;
for ( int i = 0, remainder = textCapacity - currentText; i < remainder; i++ ) {
newMessage[i] = message[i];
std::cout << newMessage; //here nothing is printed
}
}
But nothing is printed.
Only if I change newMessage to newMessage[i] everything is good. And I dont undestand why?

newMessage is an empty std::string. Doing [i] to it is accessing invalid memory. The string is always empty, and you're just writing to invalid memory. That's a recipe for disaster, and you're (un)lucky it's not crashing on you.
I'm not sure what message[i] is, but you probably want newMessage[i] = message[i]. But you might as well skip the temporary newMessage variable and just print out message[i] itself.

newMessage is an empty string, so nothing will be printed. Also, std::cout is buffered, so in order to flush the buffer you should call std::endl or std::flush

I would rather change from this:
newMessage[i] = message[i];
to this:
newMessage += message[i];
And when printing:
std::cout << newMessage<<std::endl;
Using [i] on empty string is looking for trouble because your entering invalid out of bound memory. Sometimes it will do nothing sometimes your program will crash.

As Cornstalks said, you have an out-of-bounds access.
More importantly, the code is way too complex for the task. Don't use a manual loop to partially copy one std::string to another. To copy a part of message to newMessage, use substr on message and assign:
newMessage = message.substr(from_index, number_of_chars);
or the iterator-based stuff:
std::string newMessage(message.begin() + from_index, message.begin() + to_index);
The latter is more efficient. So you want
std::string newMessage(message.begin(), message.begin() + (textCapacity - currentText));

Using that string as newMessage[i] is implying that it an array of strings. Replace that line with std::string newMessage[textCapacity];.

Related

I can check if a string is null-terminated but not check it isn't yet null terminated

For the sake of me better understanding C++ strings, array and pointers; I want to know: Why is it that I can use a condition whereby I check if the index has reached the null-terminating character like this...
const char* myString = "Grandopolous";
for (int i = 0;;i++)
{
if (!myString[i])
break;
else
cout << myString[i];
}
So that works just fine. Here I am instead checking to see if the character equals something other than the null-terminating character and so I expect that if it doesn't the result should be not 0 and the condition should be true. but this does not work, and I simply cannot fathom why:
const char* myString = "Grandopolous";
for (int i = 0;;i++)
{
if (myString[i])
cout << myString[i];
}
This does not work on my machine and crashes, also it outputs a lot of unreadable error messages mixed with strange symbols. I don't think that part matters although it is the first time error have been printed to my console application instead of the debug console.
The reason I mentioned pointers is because I managed to get the condition to work using pointers instead of the array index syntax which I find much easier to read.
So could someone please help me understand why my first bit of code is valid and why my second is not.
It does work. The check for null isn't the problem.
Your program crashes because you got rid of the break so your program overruns the array then continues forever into the abyss.
Your debugger would surely have revealed this to you as you stepped through the program, observing i.
To reverse the logic of your first example, write:
const char* myString = "Grandopolous";
for (int i = 0;;i++)
{
if (myString[i])
cout << myString[i];
else
break;
}

libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string Error?

Here is a function I'm writing that receives a string of words separated by spaces and adds each word to an array. I keep getting an error that says "libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string." I can't seem to find what the error is.
void lineParser(string line, string words[])
{
string word = "";
int array_index = 0;
int number_of_words = 1;
int string_index = 0;
while (string_index < line.length())
{
if (line.substr(string_index,1) != " ")
{
int j = string_index;
while (line.substr(j,1) != " ")
{
word += line.substr(j,1);
j++;
}
words[array_index] = word;
array_index++;
word = "";
number_of_words++;
string_index = j;
}
else
{
string_index++;
}
}
}
Your variable j is allowed to increase without bounds checking also. It will eventually excede the length of the string you're using it as an index into (.line.substr(j,1)).
A very bad answer would be to add a space at the end of your string line before searching for ' ' characters. A much better answer is to check j against the length of the string before calling any function which accesses the characters in the string using it as an index.
You've got no array bounds checking when accessing words. If the array passed in doesn't have enough space allocated, you'll run past the end of the array.
As you've pointed out below, that isn't necessarily the problem, but it's impossible to say without seeing the rest of your code (main, for example). It's also really bad code, you should never just assume that you know the length of an array, ever. You're using C++, make use of STL containers. It will save you untold headaches associated with arrays.

strcpy() is not copying properly c++

Recently I made a program, it has a character array board[8][8][2];
It is basically meant to be a 8X8 board which can store '2' lettered strings. I am not providing the complete code.
But here is the problem.
for (j = 0; j < 8; j++) {
strcpy(board[1][j], P[j].sym);
}
cout << board[1][1] << endl;
Here P[1].sym="P1" and P[0].sym="P0" and P[2].sym="P2"
Therefore P[j].sym is basically a two letter string and board[1][j] should also be a two letter string.
But the output for
cout << board[1][1] << endl;
is given as P1P2P3P4P5P6P7
and the output for
cout << board[1][0] << endl;
is given as P0P1P2P3P4P5P6P7
For
cout << board[1][5] << endl;
P5P6P7 is the output.
To remove any doubt the whole board[8][8][[2] is already initialised
and all of P[j].sym are already initialised.
If it helps here is the code for the initialisation of P:
#include <iostream>
#include <string.h>
using namespace std;
class Game
{
public:
char board[8][8][2];
char *****possibilities;
};
class Pawn : virtual public Game {
public:
char sym[2];
int possiblec[4][2];
Pawn() { }
Pawn(int i) {
char a[2];
a[0] = 'P';
a[1] = (char)(i + 48);
strcpy(sym, a);
}
};
And here somewhere else in the program I did
Pawn P[8];
It calls the constructor and then later on I called the parameterised contructor explicitly.
for (int i = 0; i < 8; i++) {
P[i] = i;
}
After this I checked for different values of P[j].sym and all of them return the perfect values I wanted.
But not when I'm using strcpy() What is the problem here. This program is just a practice program to get a hang of it.
Character arrays in C++ ( and C ) are terminated with a Null character ('\0' ) . So, even if you need to store just two characters in your string, you must have an extra space to store the Null character.
A character array which does not terminate with a Null character can lead to a lot of other problems. It is a wrong practice.
If your character array does not terminate with a Null character, you will get a lot of problems when you call functions such as strcpy() , strcat() , etc...
So, you should change
char board[8][8][2]
to
char board[8][8][3]
And if you have any other strings just like this one, then leave one extra space in them as well.
The reason your code behaved as such is because you got lucky.
Functions such as strcpy() , strcat() all continue to copy ( or append ) until they encounter a Null Character ( which is numerically equal to zero ). So, it continues to do so until the Null character is encountered. But if there is no Null character, then you will most probably get Undefined Behavior. In your case, you just got lucky.
I will show you a brief working of strcpy() ( from here )
char * strcpy(char p, const char * q) {
while (*p++=*q++);
//there's also a return p; statement at the end
}
That is the function.
the while loop executes until it encounters false, and the equivalent for false is 0. So, when it encounters a Null character ( which is also numerically equal to 0 ), the while loop terminates and the copying is complete, and the function ends. So, if there is no Null character at the end, it will give you undefined Behavior.
You can refer man for more info about them
You should always reserve one extra character because strings in C and C++ are null terminated, which that they need one extra character to sign the end of the string.
So, please, change
board[8][8][2]
to
board[8][8][3]
as well as sym[2] to sym[3], a[2] to a[3] (generally add one to the length of all strings) and try again.
By looking at the manual pages for strcpy:
Copies the C string pointed by source into the array pointed by
destination, including the terminating null character (and stopping at
that point).
This means that that function will stop only when it encounters the null character. That's why it would fail if there wasn't any present. But, by setting one character at a time, there's obviously no such problem visible (it will become visible later on, if you try to execute a function that stops only when it encounters a null character and there are plenty of them).
Strings are null ('\0') terminated in C++. When you pass in an character array to printf it stops printing at the null character. I'm guessing the only reason it stopped printing at P7 is because you got lucky and the next memory location happens to be storing Null. You need to make your char arrays at least 1 character longer than the string you want to store.

C++ is mixing my strings?

I have this really simple c++ function I wrote myself.
It should just strip the '-' characters out of my string.
Here's the code
char* FastaManager::stripAlignment(char *seq, int seqLength){
char newSeq[seqLength];
int j=0;
for (int i=0; i<seqLength; i++) {
if (seq[i] != '-') {
newSeq[j++]=seq[i];
}
}
char *retSeq = (char*)malloc((--j)*sizeof(char));
for (int i=0; i<j; i++) {
retSeq[i]=newSeq[i];
}
retSeq[j+1]='\0'; //WTF it keeps reading from memory without this
return retSeq;
}
I think that comment speaks for itself.
I don't know why, but when I launch the program and print out the result, I get something like
'stripped_sequence''original_sequence'
However, if I try to debug the code to see if there's anything wrong, the flows goes just right, and ends up returning the correct stripped sequence.
I tried to print out the memory of the two variables, and here are the memory readings
memory for seq: http://i.stack.imgur.com/dHI8k.png
memory for *seq: http://i.stack.imgur.com/UqVkX.png
memory for retSeq: http://i.stack.imgur.com/o9uvI.png
memory for *retSeq: http://i.stack.imgur.com/ioFsu.png
(couldn't include links / pics because of spam filter, sorry)
This is the code I'm using to print out the strings
for (int i=0; i<atoi(argv[2]); i++) {
char *seq;
if (usingStructure) {
seq = fm.generateSequenceWithStructure(structure);
}else{
seq = fm.generateSequenceFromProfile();
}
cout<<">Sequence "<<i+1<<": "<<seq<<endl;
}
Now, I have really no idea about what's going on.
If you can use std::string, simply do this:
std::string FastaManager::stripAlignment(const std::string& str)
{
std::string result(str);
result.erase(std::remove(result.begin(), result.end(), '-'), result.end());
return result;
}
This is called "erase-remove idiom".
This happens because you put the terminating zero of a C string outside the allocated space. You should be allocating one extra character at the end of your string copy, and adding '\0' there. Or better yet, you should use std::string.
char *retSeq = (char*)malloc((j+1)*sizeof(char));
for (int i=0; i<j; i++) {
retSeq[i]=newSeq[i];
}
retSeq[j]='\0';
it keeps reading from memory without this
This is by design: C strings are zero-terminated. '\0' signals to string routines in C that the end of the string has been reached. The same convention holds in C++ when you work with C strings.
Personally, I think you would be best off using std::string unless you have really very good reason otherwise:
std::string FastaManager::stripAlignment(std::string value)
{
value.erase(std::remove(value.begin(), value.end(), value.begin(), '-'), value.end());
return value;
}
When you are using C strings you need to realize that they are null-terminated: C strings reach up to the first null character found. With code you posted you introduced an out of range assignment as you allocated 'j' elements and you assign to retSeq[j + 1] which is two character past the end of the string (surely you mean retSeq[j] = 0; anyway).

Simple Sentence Reverser in C++

I'm trying to build a program to solve a problem in a text book I bought recently and it's just driving me crazy.
I have to built a sentence reverser so I get the following:
Input = "Do or do not, there is no try."
Output = "try. no is there not, do or Do"
Here's what I've got so far:
void ReverseString::reversalOperation(char str[]) {
char* buffer;
int stringReadPos, wordReadPos, writePos = 0;
// Position of the last character is length -1
stringReadPos = strlen(str) - 1;
buffer = new char[stringReadPos+1];
while (stringReadPos >= 0) {
if (str[stringReadPos] == ' ') {
wordReadPos = stringReadPos + 1;
buffer[writePos++] = str[stringReadPos--];
while (str[wordReadPos] != ' ') {
buffer[writePos] = str[wordReadPos];
writePos++;
wordReadPos++;
}
} else {
stringReadPos--;
}
}
cout << str << endl;
cout << buffer << endl;
}
I was sure I was on the right track but all I get for an output is the very first word ("try.") I've been staring at this code so long I can't make any headway. Initially I was checking in the inner while look for a '/0' character as well but it didn't seem to like that so I took it out.
Unless you're feeling masochistic, throw your existing code away, and start with std::vector and std::string (preferably an std::vector<std::string>). Add in std::copy with the vector's rbegin and rend, and you're pretty much done.
This is utter easy in C++, with help from the standard library:
std::vector< std::string > sentence;
std::istringstream input( str );
// copy each word from input to sentence
std::copy(
(std::istream_iterator< std::string >( input )), std::istream_iterator< std::string >()
, std::back_inserter( sentence )
);
// print to cout sentence in reverse order, separated by space
std::copy(
sentence.rbegin(), sentence.rend()
, (std::ostream_iterator< std::string >( std::cout, " " ))
);
In the interest of science, I tried to make your code work as is. Yeah, it's not really the C++ way to do things, but instructive nonetheless.
Of course this is only one of a million ways to get the job done. I'll leave it as an exercise for you to remove the trailing space this code leaves in the output ;)
I commented my changes with "EDIT".
char* buffer;
int stringReadPos, wordReadPos, writePos = 0;
// Position of the last character is length -1
stringReadPos = strlen(str) - 1;
buffer = new char[stringReadPos+1];
while (stringReadPos >= 0) {
if ((str[stringReadPos] == ' ')
|| (stringReadPos == 0)) // EDIT: Need to check for hitting the beginning of the string
{
wordReadPos = stringReadPos + (stringReadPos ? 1 : 0); // EDIT: In the case we hit the beginning of the string, don't skip past the space
//buffer[writePos++] = str[stringReadPos--]; // EDIT: This is just to grab the space - don't need it here
while ((str[wordReadPos] != ' ')
&& (str[wordReadPos] != '\0')) // EDIT: Need to check for hitting the end of the string
{
buffer[writePos] = str[wordReadPos];
writePos++;
wordReadPos++;
}
buffer[writePos++] = ' '; // EDIT: Add a space after words
}
stringReadPos--; // EDIT: Decrement the read pos every time
}
buffer[writePos] = '\0'; // EDIT: nul-terminate the string
cout << str << endl;
cout << buffer << endl;
I see the following errors in your code:
the last char of buffer is not set to 0 (this will cause a failure in cout<
in the inner loop you have to check for str[wordReadPos] != ' ' && str[wordReadPos] != 0 otherwise while scanning the first word it will never find the terminating space
Since you are using a char array, you can use C string library. It will be much easier if you use strtok: http://www.cplusplus.com/reference/clibrary/cstring/strtok/
It will require pointer use, but it will make your life much easier. Your delimiter will be " ".
What where the problems with your code and what are more cplusplusish ways of doing is yet well written. I would, however, like to add that the methodology
write a function/program to implement algorithm;
see if it works;
if it doesn't, look at code until you get where the problem is
is not too productive. What can help you resolve this problem here and many other problems in the future is the debugger (and poor man's debugger printf). It will make you able to see how your program actually works in steps, what happens to the data etc. In other words, you will be able to see which parts of it works as you expect and which behaves differently. If you're on *nix, don't hesitate to try gdb.
Here is a more C++ version. Though I think the simplicity is more important than style in this instance. The basic algorithm is simple enough, reverse the words then reverse the whole string.
You could write C code that was just as evident as the C++ version. I don't think it's necessarily wrong to write code that isn't ostentatiously C++ here.
void word_reverse(std::string &val) {
size_t b = 0;
for (size_t i = 0; i < val.size(); i++) {
if (val[i] == ' ') {
std::reverse(&val[b], &val[b]+(i - b));
b = ++i;
}
}
std::reverse(&val[b], &val[b]+(val.size() - b));
std::reverse(&val[0], &val[0]+val.size());
}
TEST(basic) {
std::string o = "Do or do not, there is no try.";
std::string e = "try. no is there not, do or Do";
std::string a = o;
word_reverse(a);
CHECK_EQUAL( e , a );
}
Having a multiple, leading, or trailing spaces may be degenerate cases depending on how you actually want them to behave.