Output letters one at a time in C++? - c++

I've seen a couple of solutions to this question, but I'm still running into an issue. I've tried several of the solutions I've seen on this site, but I keep having the same issue. I'm not sure how to make this work, and I'm also not sure why it's not working, since I'm really new to C++.
A brief explanation of what I am attempting to do: I'm writing a simple old-school text-based story/game for a video game design club at my school, and at several points I have the user make decisions, or input things such as their name, which is then used in an output line, as it would be referenced several times. I have had no problem doing that, using something simple like this:
#include <iostream>
#include <string>
#include <limits>
#include <windows.h>
using namespace std;
int main(){
string name, place ;
cout << "???: What is your name? ";
getline (cin, name);
cout << "???: Hello, " << name << "!\n" << "\n";
}
My problem is that I'd like to have the text appear one character at a time, like dialogue, but whenever I try to use something I've seen written by others, it doesn't seem to like it very much. The only one that I tried that I can now find again is this:
#include <iostream>
#include <unistd.h> // include <windows.h> on windows
// function to output as if it was being typed
void type_text(const std::string& text)
{
// loop through each character in the text
for (std::size_t i = 0; i < text.size(); ++i)
{
// output one character
// flush to make sure the output is not delayed
std::cout << text[i] << std::flush;
// sleep 60 milliseconds
usleep(60000); // use Sleep on windows
}
}
int main()
{
type_text("Hej hej hallÄ!");
}
Apparently there is some sort of conflict regarding my attempt to output the name back to the user when I try to use that code with what I've written. I'm not really sure what the problem is, since I'm so new to C++, can anyone help me out?

Consider using std::this_thread::sleep_for, as it is standard C++11. Example:
#include <iostream>
#include <thread> // standard C++11
// function to output as if it was being typed
void type_text(const std::string& text)
{
// loop through each character in the text
for (std::size_t i = 0; i < text.size(); ++i)
{
// output one character
// flush to make sure the output is not delayed
std::cout << text[i] << std::flush;
// sleep 60 milliseconds
std::this_thread::sleep_for(std::chrono::milliseconds(60));
}
}
int main()
{
type_text("Hello, World!");
}
If you have access to a C++14 compiler, you can simply make use of the std::chrono user-defined literals and have a more "natural" syntax:
using namespace std::literals;
std::this_thread::sleep_for(60ms);

Related

Is there a way to stop an ongoing loop by typing something in C++?

I was wondering if there is a way to stop an ongoing loop in C++ by writing something while the code is being executed.
For example, if I have an infinite loop in my program that types the letter "A" every second. I want to be able to write "finish" to act like a sudden "break" function whenever I want in the middle of executing the program.
yeah you can do that. how about this:
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <string>
#include <thread>
#include <unistd.h>
void wait() {
for (std::string line; std::getline(std::cin, line);) {
if (line.compare("stop!!") == 0) {
std::cout << "stopping\n";
exit(0);
}
}
}
int main() {
std::thread wait_for_your_command (wait);
while (1) {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "foo\n";
}
}
You have two choices.
One is multi-threading, just like #marcelo827 said.
The other is that you can use the get-char function with NON-BLOCKING.
string str;
while (true)
{
char ch = get_char_non_blocking();
str += ch;
if (str == "whatever")
{
break;
}
// print A per second
}
However, C/C++ Standard library doesn't provide us the function get_char_non_blocking().
getch() is what you need, this function works on Windows(#include <conio.h>) and on Linux(#include <ncurses.h>, ofc you may need install the library ncurses by yourself).
BTW, multi-threading shouldn't be your first choice unless you have no other choice or unless you know exactly what you are doing. Because multi-threading has a price.

C++ - Looping through vector runs infinitely

I'm new to C++, came from Java (started learning yesterday).
I'm trying to loop over the elements of a vector. For some reason when I do this, it endlessly outputs empty lines.
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::string expression = "5+4";
std::vector<char> characters(expression.begin(), expression.end());
for (char c : characters) {
std::cout << c << std::endl;
}
}
I keep running into this problem, I have no clue why it is doing this.
I tried searching if other people had this problem, but I couldn't find any questions about it or answers... what am I doing wrong?
EDIT:
I'm using MinGW
GIF or it didn't happen
I'm not an expert in CPP, but i assume your code is inserting string to the vector and iterate through the vector, if so, heres the code :
#include <iostream>
#include <string>
#include <vector>
using namespace std; //i add this line to remove the "std" in every line
int main()
{
string expression = "5+4";
vector <char> characters(expression.begin(), expression.end());
for (int i=0; i< characters.size(); i++)
{
cout << characters[i] << endl;
}
}
An explanation that i can tell you is, you do not printing the vectors with its index so it'll have some bug also the looping i use i think more clear to see.

convert single back slash to double back slash in c++

I have one path e.g. "C:\home\my folder". I want to convert it into "C:\\home\\my folder". Please suggest me how can i use any function call to do this?
Thanks in advance.
The best way to do this could be by using the Boost string algorithm library.
http://www.boost.org/doc/libs/1_46_1/doc/html/string_algo.html
Using the following command :
std::string newPath = boost::replace_all_copy(testStr, "\", "\\");
This would result in the replaced and newly formed string.
Hope this helps.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream lire("data.txt",ios::in);
string text ;
getline(lire,text); //text contains your repertory
cout<<text<<endl;
for (int i = 0 ; i < text.size();i++)
{
if(text[i] == '\\')
{
text.insert(i,"\\") ;
i++;
}
}
cout<<text<<endl;
return 0;
}
The following program works for me.
#include <iostream>
#include <string>
#include <Shlobj.h>
int main()
{
std::string myPath;
std::cout << "Enter path to create: ";
std::cin >> myPath;
std::cout << "Path from user: " << myPath << "\n";
::SHCreateDirectoryEx(nullptr, myPath.c_str(), nullptr);
return 0;
}
Sample Run
As you can see the path taken from user input only uses a single back slash but the directory is successfully created.
Enter path to create: C:\a_path
Path from user: C:\a_path
I think you chasing the wrong problem, assuming the reason you asked this question is because your call to the SHCreateDirectoryEx function failed.
Notes:
When some Win32 API functions fail (e.g., CraeateDirectory) you must call GetLastError to actually get the error code, but this isn't the case for SHCreateDirectoryEx (i.e., it returns the failure code directly).
The SHCreateDirectoryEx function also works for me if I use forward slashes.

No match for 'operator>>'

I can't figure out why it says this. I am new as you can probably tell... here is the code:
#include <iostream>
using namespace std
int main() {
if (cin >> "hi"
cout << "hello"
return 0;
}
"The thing you were using" (read: your compiler) wanted you to end your using namespace std statement with a semicolon, not to dump one at the start of a function definition.
Your code has a number of extreme and baffling syntax errors, to the extent that it's not even clear what you're trying to accomplish.
Below is a hint to get you started but, from now on, I strongly recommend that you read a good, peer-reviewed C++ book and learn the language before asking any further questions about nonsense code!
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input;
getline(cin, input);
if (input == "hi") {
cout << "hello" << endl;
}
return 0;
}

getline() not reading first lines

I am c++ beginner and this is for school..
I am trying to read a file about 28kb big. The program works but it doesnt print the first 41 lines. It works fine with a smaller file.
At first i was reading into a char array and switch it to strings.
i also tried changing the log buffer but it apparently it should be big enough..
I feel like this should be very simple, but just cant figure it out..
Any help will be greatly apreciated..
Thanks!
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <cstdio>
#include <cerrno>
using namespace std;
struct espion
{
char nom[30];
char pays[20];
char emploi[29];
};
int main()
{
const int MAX_NOM = 30, MAX_PAYS = 20, MAX_EMPLOI = 29;
char nomFichier[50] = "espion.txt";
ifstream aLire;
aLire.open(nomFichier, ios::in|ios::binary);
if(!aLire.is_open()){
exit(EXIT_FAILURE);
}
std::string infoEspion;
while(aLire)
{
infoEspion.clear();
std::getline(aLire, infoEspion);
cout << infoEspion ;
}
aLire.close();
system("pause");
return 0;
}
From the system("pause"), it looks like you're running on Windows. With ios::binary, the end-of-line marker is not translated, and the cout << infoEspion; statement prints these "raw" lines in such a way that all of the lines are written on top of each other. (More specifically, each line will end with a return but no newline, so the cursor goes back to the start of the same line after executing each cout statement.) If you take out the ios::binary, you will echo all of the input on a single, very long line. Changing the statement to cout << infoEspion << endl; will echo all of the lines.