I have a void function that recursively prints an AVL tree in order, using a comma and a space between every key.
After the void function is called, I want to remove the last comma and space, but I am not sure how. I tried doing std::cout << '\b' << '\b', but it doesn't do anything.
What I'm trying is something like:
void printInoder(root){
InorderHelper(root);
cout << '\b' << '\b' << endl;
}
The name backspace is a bit misleading. It doesn't print a space.
If the output ends with , you probably want std::cout << "\b\b \b\n";. That is, step two steps back, print a space over the , and then step one step back. Since you do a newline last, the last \b can be omitted.
std::cout << "\b\b \n";
It would probably be better to fix it at the source and not print the characters you want to erase at all.
Related
I am trying to take text input from the user and compare it to a list of values in a text file. The values are this:
That line at the end is the cursor, not a straight line, but it doesn't matter. Anyway, I sort by word and produce the values, then check the values. Semicolon is a separator between words. All the data is basic to get the code working first. The important thing is that all the pieces of data have newlines after them. No matter what I try, I can't get rid of the newlines completely. Looking at the ASCII values shows why, My efforts remove only the new line, but not the carriage return. This is fine most of the time, but when comparing values they won't be the same because the one with the carriage return is treated as longer. Here is the important parts of the code:
int pos = 0;
while (pos != std::string::npos)
{
std::string look = lookContents.substr(pos+1, lookContents.find("\n", pos + 1) - pos);
//look.erase(std::remove(look.begin(), look.end(), '\n'), look.end());
//##
for (int i = 0; i < look.length(); i++)
{
std::cout << (int)(look[i]) << " ";
}
std::cout << std::endl;
std::cout << look << ", " << words[1] << std::endl;
std::cout << look.compare(0,3,words[1]) << std::endl;
std::cout << pos << std::endl;
//##
//std::cout << look << std::endl;
if (look == words[1])
{
std::cout << pos << std::endl;
break;
}
pos = lookContents.find("\n", pos + 1);
}
Everything between the //## are just error checking things. Heres what is outputs when I type look b:2
As you can see, the values have the ASCII 10 and 13 at the end, which is what is used to create newlines. 13 is carriage return and 10 is newline. The last one has its 10 remove earlier in the code so the code doesn't do an extra loop on an empty substring. My efforts to remove the newline, including the commented out erase function, either only remove the 13, or remove both the 10 and 13 but corrupt later data like this:
Also, you can see that using cout to print look and words1 at the same time causes look to just not exist for some reason. Printing it by itself works fine though. I realise I could fix this by just using that compare function in the code to check all but the last characters, but this feels like a temporary fix. Any solutions?
My efforts remove only the new line, but not the carriage return
The newline and carriage control are considered control characters.
To remove all the control characters from the string, you can use std::remove_if along with std::iscntrl:
#include <cctype>
#include <algorithm>
//...
lookContents.erase(std::remove_if(lookContents.begin(), lookContents.end(),
[&](char ch)
{ return std::iscntrl(static_cast<unsigned char>(ch));}),
lookContents.end());
Once you have all the control characters removed, then you can process the string without having to check for them.
This is a simplified and more informative version of a question that has now been deleted.
BACKGROUND
I am currently trying to familiarize myself with basic C++ programming and decided to make a game of hangman. However, I noticed that an integer variable called preset_count—which is meant to count how many letters have been pre-guessed by the game— always returns a value of 0 in the main() function whereas in other functions, it has a value of 2 (or anything greater than 0).
What I am trying to accomplish here is that the program will automatically fill in the vowels of the word the player is trying to guess. Depending on how many vowels are filled in, the score the player gets when guessing a character right increases.
For example, the player is trying to guess the word "eraser," so the hangman program will print out
"e _ a _ e _ " they will gain 334 points if they guess correctly.
In a word like "circle," though (which will be printed as "_ i _ _ _ e ") the player will gain 250 points per guess because of the fact that the player has to guess 4 characters instead of 3.
THE ISSUE AND CODE
In order to accomplish this, I added code meant to count how many vowels have been filled in by the game in a special function.
The code below is a simplified version of the one in the actual hangman program that re-creates the issue I have with the program. See, the game outputs a different value of the preset_count value in each function.
Essentially, the main() function has a
cout << "preset_count in main(): " << preset_count;
//This line of code prints out 0. However, the variant of this in find_preset():
cout << "preset_count in find_preset(): " << preset_count;
//Which, on the other hand, prints out 3.
Is there any reason behind these contradictory variable reports? Is there any way to solve this?
#include <iostream>
using namespace std;
void find_preset (int, const string, string); //Prototyping for find_preset()
int main() {
int preset_count = 0; //Amount of times a character in PRESET_LETTERS appears in the word variable.
const string PRESET_LETTERS = "AEIOUaeiou"; //The letters the program is looking out for.
string word = "eraser"; //The word being analyzed.
cout << "\nmain(): main() executed, variables declared, about to execute find_preset() function.";
find_preset(preset_count, PRESET_LETTERS, word); //find_preset() function; finds how many PRESET_LETTERS characters are in word.
cout << "\nmain(): find_preset() finished executing.\n"; //Announces that find_preset() function finished executing.
cout << "\n\nDEBUG word: " << word << endl; //Report on the set word value.
cout << "DEBUG preset_count in main(): " << preset_count << endl << endl; //Report on preset_count's value in main().
//This is where my issue takes place in. This reports a value whereas in find_preset(), the value of preset_count is 2.
return 0;
}
//find_preset() function; finds how many PRESET_LETTERS characters are in word.
void find_preset(int preset_count, const string PRESET_LETTERS, string word) {
int word_index = 0; //How many characters of word that find_preset() has gone through.
cout << "\nfind_preset() executed, now counting amount of instances of PRESET_LETTERS in word.";
//While word_index is less than the size of word. While the entire word variables hasn't been scanned yet.
while (word_index < word.size()) {
//If a PRESET_LETTERS character is found in word.
if(word.find(PRESET_LETTERS)) {
preset_count++; //preset_count increased by 1.
cout << "\nfind_preset(): preset_index and preset_count increased by 1."; //Reports preset_count++; has been executed.
}
word_index++; //Word index increased by 1.
cout << "\nfind_preset(): word_index increased by 1."; //Reports that word_index++; has been executed.
}
cout << "\nfind_preset(): while (word_index < word.size()) finished executing, now printing debug menu for find_preset().\n";
//Reports that the while loop has finished executing.
cout << "\n\nDEBUG: preset_count in find_preset(): " << preset_count; //Report on preset_count's value in find_preset().
//This is also where my issue takes place in. This reports that preset_count's value is 2 whereas in main, it reports 0.
cout << "\nDEBUG: word_index value: " << word_index << endl << endl; //Report on word_index's value.
}
The arguments in C++ are copies of what are passed by default. Therefore, modifications of arguments in callee functions won't affect what are passed in caller. You should add & to make the arguments to references if you want to have functions modify what are passed.
Both declaration and definition should be modified.
void find_preset (int&, const string, string); //Prototyping for find_preset()
void find_preset (int& preset_count, const string PRESET_LETTERS, string word) //find_preset() function; finds how many PRESET_LETTERS characters are in word.
{
I am having the following function:
void test(const char *nap){
if (*nap != 'D'){
test(nap+1);
std::cout << *nap;
}};
When I call the function with:
"ABCD"
Output, that I thought I would get was: ABC, however, in reality, its CBA. Can anyone explain to me where do I make mistake?
You call it in the wrong order. Revert that:
test(nap+1);
std::cout << *nap;
like this
std::cout << *nap;
test(nap+1);
Your recursion is to go to the end of the text string and to then go backwards printing each character.
In other words your function keeps calling itself until it reaches end of string. At that point it returns to where it called itself and the next step is to print the current character.
Then you return to where it called itself again and the next step is to print the current character.
The result is that you traverse the string until the end of string by the recursive calls. Once you reach the end of string you start unwinding the series of recursive calls. At each return you print the current character.
Try the following which will print the current character and then call itself to print the next character instead. When it reaches the end of the string it will unwind the recursive calls.
void test(const char *nap) {
if (*nap != 'D'){
std::cout << *nap;
test(nap+1);
}
};
because the std::cout is after calling the recursion ( )..
test(nap+1);
std::cout << *nap;
That is parent feeds children before eating.
The below will get what you want:
std::cout << *nap;
test(nap+1);
I am beginner at C++, my question is can I remove endl the one at the end of cout like :
cout<<" "<<endl;
I don't want return to new line . If I can't remove it, what should I do?
Elephant in the room: remove the endl from the cout.
But in case you don't own that code, you could try "\033[F", which, if your terminal supports it, moves you to the previous line.
Another possibility would be to redirect the cout buffer using rdbuf to an ostream that you control. You could (i) redirect, (ii) call the function that writes the errant cout with the new line and (iii) inspect your ostream and write to the original buffer, this time omitting the endl. Switch everything back once you're done.
Yes of course you do not need to use std::endl every time you use <<. As an example a simple way to print a vector with spaces between the elements would look like:
std::vector<int> foo = {1,2,3,4,5};
for (auto e : foo)
std::cout << e << " ";
Here we never use a endl. You cout also just use \n at the end of a string literal and that will put a newline in the buffer as well.
std::cout << "test\n";
std::cout << "this will be on a new line";
Notice that I don't put a newline in the last cout<< so if there is anymore output it will start off right after the "e" in "line".
Yes you can remove endl. It is an optional parameter to the << stream operator of which there are many. If you don't include it then a new Carriage Return/Line Feed character will not be output and therefore text will appear on the same line in the output (presumably console).
For example
cout << "Hello, World" << endl;
would become:
cout << "Hello, World";
or to make the point another way you could write:
cout << "Hello,";
cout << " World";
There are lots of other examples out there too, here's one for starters: http://www.cplusplus.com/doc/tutorial/basic_io/
cout<<"Your message here.";
It's as simple as that. Were you trying to do something like...
cout<<"Your message here."<<; ....? This is wrong as:
The << operator signifies that something comes after the "" part. You don't have any in this case.
So I have a while look that checks every character in a file.
while (infile.get(ch))
The problem is that in the same loop I have to check the next character to check for some validation.
Is there anyway I could move the next character while keeping track of the current one?
Thanks
Use the peek() method so you will be able to look at the next character before extracting it. Here's an example:
std::istringstream iss("ABC");
for (char c; iss.get(c); )
{
std::cout << "Current character is: " << c << std::endl;
if (iss.peek() != EOF)
std::cout << "Next character is: " << (char)iss.peek();
}
This should output:
Current character is: A
Next character is: B
Current character is: B
Next character is: C
Current character is: C