Specific answer to specific text - c++

I'm looking for a long time for a code that displays a different text depending on what you tipe. I didn't work at the app I wanted to make for a long time but I think this is what I tried (Remember I'm a begginer):
char text
cout << "Insert Text: " << text << endl;
if (text== "Stop")
{
cout << "Ok. Bye!" << endl;
}

you need to use cin to get something from the user. Also char means 'one single character'. Use strings instead
std::string text;
cout << "Insert Text: " << endl;
cin >> text;
if (text == "Stop")
{
cout << "Ok. Bye!" << endl;
}

Related

How would I print a multi-line (non-standard) unicode string of text in C++? Updated for Clarity! (hopefully)

Rewriting this question with a bit more knowledge on what I'm requesting; (Thank you James Risner and Turtle for your assistance, but I didn't word this correctly and got different responses than what was needed)
I am currently in the process of writing a program for my class in which I print out non-standard Unicode characters in a string. These characters are direct copies from a website, and not in u\ #### standard copy, but rather the unicode characters pre-selected. The program I am running this on is Clion, building my program using mingw's ninja build settings.
My issue that I'm experiencing is that my output, rather than the unicode characters, is instead a random array of (I think) unrelated characters. Printing this in Clion's Debug menu outputs the proper output, but printing it in the runtime or in its own external file all output the issue.
Below is an exact copy of my code (character for character) DO NOT REUSE PLEASE :(
#include <iostream>
#include <string>
#include <windows.h>
#define _WIN32_WINNT 0x0500
#include <thread>
#include <chrono>
#include <random>
using namespace std;
static int Range(int start, int end){
random_device rd;
mt19937 rng(rd());
uniform_int_distribution<int> dist(start,end);
return dist(rng);
}
int main() {
system("color 0F");
HWND consoleWindow = GetConsoleWindow();
int windowSize = 390;
MoveWindow(consoleWindow, windowSize,windowSize,windowSize,windowSize, TRUE); // This program and the one below it not only locks the window size, but also locks the window at a fixed display pixel length/width
SetWindowLong(consoleWindow, GWL_STYLE, GetWindowLong(consoleWindow, GWL_STYLE) & ~WS_MAXIMIZEBOX & ~WS_SIZEBOX);
ShowScrollBar(GetConsoleWindow(), SB_VERT, 0);
string name = "\033[91m▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n\033[92m███╗░░░███╗░█████╗░██████╗░███████╗███╗░░██╗██╗\n\033[93m████╗░████║██╔══██╗██╔══██╗██╔════╝████╗░██║██║\n\033[94m██╔████╔██║██║░░██║██║░░██║█████╗░░██╔██╗██║██║\n\033[95m██║╚██╔╝██║██║░░██║██║░░██║██╔══╝░░██║╚████║██║\n\033[96m██║░╚═╝░██║╚█████╔╝██████╔╝███████╗██║░╚███║██║\n\033[91m╚═╝░░░░░╚═╝░╚════╝░╚═════╝░╚══════╝╚═╝░░╚══╝╚═╝\n\033[92m▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n";
float balance = Range(1,50000);
float withD, cSelect;
int x = 0;
while (name[x] != '\0') {
cout << name[x] << flush;
this_thread::sleep_for(chrono::milliseconds(1));
x++;
}
Sleep(2);
std::cout << '\n' << endl;
string bottomBar = "\033[93m░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░\n";
string systName = "\033[94mModeni Systems LLC";
cout << " ";
cout << systName << "\n";
std::cout << '\n' << endl;
int y = 0;
while (bottomBar[y] != '\0') {
cout << name[y] << flush;
this_thread::sleep_for(chrono::milliseconds(1));
y++;
}
string Input;
cout << "\n \033[92mPlease Input your Name...\n\n ";
getline(cin, Input);
cout << endl;
cout << " Welcome " << Input << "!" << endl;
cout << " Please select a number from the options below!\n" << endl;
cout << bottomBar << endl;
cout << " 1.) View your Balance\n 2.) Make a withdrawal\n 3.) Deposit\n 4.) Customer Support\n 5.) Log Out Securely\n" << endl;
cout << bottomBar << endl;
cin >> cSelect;
while(cSelect != 5){
if(cSelect==1){
cout << "Your current balance is... " << balance << " dollars!\n \n" << endl;
cout << "Please select a number from the options given below!\n" << endl;
cout << bottomBar << endl;
cout << " 1.)View your Balance\n 2.)Make a withdrawal\n 3.)Deposit\n 4.)Customer Support\n 5.)Log Out Securely" << endl;
cin >> cSelect;
} else if(cSelect==2){
cout << "Please enter the amount you'd like to withdraw!\n" << endl;
cin >> withD;
if(withD>balance){
cout << "Sorry, you do not have that much money! Please try again... " << endl;
} else if(withD<=balance) {
balance = balance - withD;
cout << "Successfully taken out " << withD << " dollars!\n" << "Your new balance is " << balance << " dollars!" << endl;
cout << "Please select a number from the options given below!\n" << endl;
cout << bottomBar << endl;
cout << " 1.)View your Balance\n 2.)Make a withdrawal\n 3.)Deposit\n 4.)Customer Support\n 5.)Log Out Securely" << endl;
cin >> cSelect;
}
} else if(cSelect==3){
cout << "Please enter the amount you'd like to deposit!" << endl;
double depAm;
cin >> depAm;
balance = balance + depAm;
cout << "Your new balance is now " << balance << " dollars!" << endl;
cout << "Please select a number from the options given below!\n" << endl;
cout << bottomBar << endl;
cout << "1.)View your Balance\n2.)Make a withdrawal\n3.)Deposit\n4.)Customer Support\n5.)Log Out Securely" << endl;
cin >> cSelect;
} else if(cSelect==4){
cout << bottomBar << "\n" << endl;
cout << "Hello! This is Modeni's Self-Service Assistant!\n Please describe your problem below! \n" << endl;
string proB;
cin >> proB;
int chatF;
chatF = Range(0,5);
if(chatF==0){
cout << "We're so sorry to hear that! Please wait as we get you in touch with someone who can help.\n" << endl;
} else if(chatF==1){
cout << "Sorry to hear that you're currently having that problem! Please sit tight as we get you in touch with someone who can help.\n" << endl;
} else if(chatF==2){
cout << "That's not good! Please wait just a moment as we get you in touch with someone who can help.\n" << endl;
} else {
cout << "Ouch! Just give us a moment while we put you in touch with someone who can help!\n" << endl;
}
Sleep(10000);
string nameSt;
int nameVar;
nameVar = Range(0,5);
if(nameVar == 1)
nameSt = "Raphael";
else if(nameVar == 2)
nameSt = "Marie";
else if(nameVar == 3)
nameSt = "Joesph";
else
nameSt = "Marian";
cout << " \033[94m░█░█ " << nameSt << " has joined the chat █░█░" << endl;
Sleep(Range(3000,8000));
cout <<"\n >> Just a moment while I look over your concern.\n" << endl;
Sleep(Range(3000,8000));
cout << " >> Alright. I'm sorry you're dealing with this problem right now. Let's put you in touch with one of our call-in agents to assist you further.\n" << endl;
Sleep(Range(3000,8000));
cout << " >> Their number is - 1-(918)-335-1300.\n" << endl;
Sleep(Range(3000,8000));
cout << " >> Is there anything else I can help you with today? \n" << endl;
return 0;
}
}
return 0;
}
I am specifically writing this program for windows, and I have yet to find a solid fix without re-writing the entirety of my code.
The intended output is photograph 1, and the actual output is photograph 2. Any and all help is appreciated!
Photograph 1
Photograph 2
There is no problem with your program. There is a problem with your display.
% cc -o modeni modeni.cpp -lc++
% ./modeni
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
███╗░░░███╗░█████╗░██████╗░███████╗███╗░░██╗██╗
████╗░████║██╔══██╗██╔══██╗██╔════╝████╗░██║██║
██╔████╔██║██║░░██║██║░░██║█████╗░░██╔██╗██║██║
██║╚██╔╝██║██║░░██║██║░░██║██╔══╝░░██║╚████║██║
██║░╚═╝░██║╚█████╔╝██████╔╝███████╗██║░╚███║██║
╚═╝░░░░░╚═╝░╚════╝░╚═════╝░╚══════╝╚═╝░░╚══╝╚═╝
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
% echo $TERM
xterm-256color
I am using a macOS system and this works with TERM=xterm-256color on both iTerm2 and Terminal.
What is TERM?
This environment variable advises applications what terminal emulation is required to display characters on screen properly. An application will use the termcap/terminfo database to look up the proper escape sequences to display colors, move or manipulative text on screen, and other effects.
I only ever see xterm-256color now. Why?
Modern terminal applications assume the output will be in xterm-256color format. Many no longer have an option to choose another format.
AFAIK there is no standard way in C++ to process unicode in standard io, and different OSs' default consoles will behave differently if you just make the unicode string as std::string to output; E.g. in Windows cmd maybe you need _setmode(_fileno(stdout), _O_U16TEXT); to show UTF-16 strings correctly.
Good news is that in C++23 there will be <print> to (hopefully, not definitely so far) help solve this troublesome problem.

How to add multiple lines to a file in C++?

I am new to C++ and write a little todo list on the console.
I am only able to add one line to a text file but when I try to add more it just won't appear on my text file.
Please take a look what I am doing wrong
//output-file stream
ofstream file;
file.open("output.txt", std::ios_base::app); //append
bool isRunning = true;
while (isRunning) {
cout << "Please select an action:" << endl;
cout << "add - adding tasks to the list" << endl;
cout << "del - deleting tasks to the list" << endl;
cout << "list - show the list" << endl;
cout << "x - to exit program" << endl;
string input;
cin >> input;
string addedTask;
if (input == "add") {
cout << "Please enter a task you like to add: " << endl;
cin.ignore();
if (std::getline(std::cin, addedTask)) {
file << addedTask << "\n";
}
else {
cout << "Failed to read line" << endl;
}
}
Why can I only add one string line? I still can't figure out the problem or am I missing something?
Did you try replacing your
file << addedTask << "\n";
by
file << addedTask << endl;
I think it should work (for me it's working)

How to iterate over string variables of a class object in C++?

So here I have a class definition of a Car and then I create a carObject with it. I want the user to input values for all the variables in the carObject. As you see here, I have managed to get user input, but my approach to this problem is inefficient in my opinion.
I notice that all of the user inputs, except for the first one are very similar. I would like to use a loop of some kind to iterate over the declaration statements, or blocks of statements, and change the variable every time. I would like to put an if statement to enter different input only for the first iteration of the loop. I know that in bash I could use a string variable to stand for the variable name, but I don't know if that's possible in C++.
Notice that the object name does not change, but only the variables that are associated with it. I also use the same word for the user input, which preferably should be changed every iteration. I also have a series of arrays which are named similarly. The purpose of these arrays is to tell the user what options are available for a particular variable.
Although I have previous programming experience, I am relatively new to C++. A block of code that would serve as a solution to my problem that involves a call to another function would suit my purposes. Here is my code below.
#include <iostream>
#include <string>
using namespace std;
class Car {
public:
string Name;
string Model;
string Color;
string Transmission;
string Category;
};
int main() {
Car CarObject;
string modelOptions [3] = { "Ferrari", "Porsche", "Nissan" };
string colorOptions [4] = { "Blue", "Red", "Green", "White" };
string transmisionOptions [2] = { "Automatic", "Manual" };
string categoryOptions [3] = { "A", "B", "C" };
cout << "Enter " << "name" << " for Car 1." << endl;
cin >> carObject.Name;
cout << endl;
cout << "Enter " << "model" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: modelOptions) {
cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Model;
cout << endl;
cout << "Enter " << "color" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: colorOptions) {
cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Color;
cout << endl;
cout << "Enter " << "transmission" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: transmissionOptions) {
cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Transmission;
cout << endl;
cout << "Enter " << "category" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: categoryOptions) {
cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Category;
cout << endl;
...
return 0;
}
void Car::InputParameter(string& param, const string &msg, const vector<string>& options)
{
cout << msg << endl;
for (const string &text: options) {
cout << " " << text;
}
cout << "." << endl;
cin >> param;
cout << endl;
}
I think you might want something like this. You just call it for each member.
This block of code:
cout << "Enter " << "category" << " for Car 1." << endl;
cout << "Options are:";
for (const string &text: categoryOptions) {
cout << " " << text;
}
cout << "." << endl;
cin >> carObject.Category;
cout << endl;
… can be replaced with a call to a function like this:
carObject.Category = userInput( "category", categoryOptions );
Clearly it returns a string (that is, a std::string).
The options argument should better be made a vector<string>.
Then just replace the other similar blocks with ditto calls to that function.
Is it a good idea to make that function a member function of Car?
No.
Consider, for example, how to then use Car in a GUI program (Graphical User Interface).

How to list how many iterations of a struct are stored inside a vector?

I'm new to c++ (and coding in general) and have recently been working with a struct held inside a vector, in this case :
struct Contact{
string name;
string address;
string phone;
string email;};
vector<Contact> contacts;
So, one of my functions involves searching through each of the contacts to find the one for which the string stored in name matches a search input. To do this I made a for loop as such:
for(int i = 0; i < contacts.size(); i++){
if(contacts[i].name == searchInput){
cout << contacts[i].address << "\n\r" << contacts[i].phone << "\n\r" << contacts[i].email;
But for some reason this was only able to find the correct contact if it was the name stored at:
contacts[0].name
and none of the others. So while trying to figure out what was wrong, I decided to do
cout << contacts.size();
which I thought should output 3, because I have only three contacts stored. Yet for some reason, it output 7. Is there anyway for me to accurately list the number of iterations of Contact stored in the contacts vector in order to get my for loop to work?
Edit for my full code:
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
struct Contact
{
string name;
string address;
string phone;
string email;
};
bool go;
bool a = false;
char command;
string endL = "\n\r";
string tab = "\t";
string line;
int i;
int counter = 0;
int contactCounter = 0;
vector<Contact> contacts;
void add(){
contacts.push_back(Contact());
int newcontact = contacts.size() - 1;
string input;
cout << "Enter the name: " << endL;
cin >> input;
contacts[newcontact].name = input;
cout << "Enter the address: " << endL;
cin >> input;
contacts[newcontact].address = input;
cout << "Enter the phone number: " << endL;
cin >> input;
contacts[newcontact].phone = input;
cout << "Enter the email address: " << endL;
cin >> input;
contacts[newcontact].email = input;
}
void search(string name){
for(int i = 0; i < contacts.size(); i++){
if(contacts[i].name == name){
cout << "Name: " << contacts[i].name << endL << "Address: " << contacts[i].address << endL << "Phone Number: " << contacts[i].phone << endL << "Email: " << contacts[i].email << endL << endL;
a = true;
}
}
if(a == false){
cout << "There is no contact under that name." << endL;
}
}
int main() {
ifstream phonebook;
phonebook.open("phonebook.txt");
if(phonebook.is_open()){
while(getline(phonebook,line)){
if(line.empty() == false){
if(counter % 4 == 0){
contacts.push_back(Contact());
contacts[contactCounter].name = line;
}else if(counter % 4 == 1){
contacts[contactCounter].address = line;
}else if(counter % 4 == 2){
contacts[contactCounter].phone = line;
}else if(counter % 4 == 3){
contacts[contactCounter].email = line;
contactCounter++;
}
counter++;
}
}
}else{cout << "an error has occurred while opening the phonebook";}
phonebook.close();
cout << contacts.size() << endL;
cout << "Enter a command." << endL << tab << "To add a contact, enter '+'" << endL << tab << "To search for a contact, enter 's'" << endL << tab << "To delete a contact, enter '-'" << endL << tab << "To quit the program, enter 'q'" << endL;
cin >> command;
while(command != 'q'){
if(command == '+'){
add();
command = '/';
}
else if(command == 's'){
string searched;
cout << "Please enter who you would like to search for: ";
cin >> searched;
search(searched);
command = '/';
}
else if(command == '-'){
cout << "Not done." << endL;
command = '/';
}
else if(command == '/'){
cout << "Enter a command." << endL << tab << "To add a contact, enter '+'" << endL << tab << "To search for a contact, enter 's'" << endL << tab << "To delete a contact, enter '-'" << endL << tab << "To quit the program, enter 'q'" << endL;
cin >> command;
}
else{
cout << "That command is invalid." << endL;
cout << "Enter a command." << endL << tab << "To add a contact, enter '+'" << endL << tab << "To search for a contact, enter 's'" << endL << tab << "To delete a contact, enter '-'" << endL << tab << "To quit the program, enter 'q'" << endL;
cin >> command;
}
}
ofstream newbook;
newbook.open("phonebook.txt");
if(newbook.is_open()){
for(int i=0; i < contacts.size(); i++){
newbook << contacts[i].name << endl;
newbook << contacts[i].address << endl;
newbook << contacts[i].phone << endl;
newbook << contacts[i].email << endl;
newbook << endL;
}
}else{cout << "there was an issue saving your contacts" << endL;}
newbook.close();
return 0;
}
There's actually nothing wrong with your code except this line
string endL = "\n\r";
Which should really only be
string endL = "\n";
\n is automatically converted to the line endings used by the system, which traditionally is \n (0x0a) on unix systems and \r\n (0x0d0a) on Windows.
But, how did this affect the program so much? Well it only takes affect after the phonebook is written at the end of the program so that phonebook.txt contains these bogus line endings that have \r\n\r at the end (on Windows). So when the file is read, it reads up until the new line \r\n and sees \rPerson Name as line after! Which explains why searching was failing.
You also may see some additional bogus contacts generated because there may be some extra \rs at the end which read as a single line each. Without looking at your phonebook.txt I can't say for certain why you have an additional 4 though I'd guess extra \rs would be the cause.
All in all, use \n for new lines.
To answer the title, vector::size() is THE way to get the number of stored objects in a vector. It's not lying to you.
Using the range based for loop ensures that you won't hit any nonexistent contacts:
for(auto&& contact: contacts)
{
// Contact contact is now accessible.
}
Also, it is probably not a good idea to store a as a global variable. What happens if you execute search twice?

Getting string length for morse code convertor keeps looping

working on one of my first programming assignments, a text to morse (and back) convertor, but for whatever reason when I introduce a piece of text with a space between words my programme goes into an endless loop and crashes. Any ideas? Sorry if this description sucks, still getting my head around programming lingo.
this is the piece of the program that isn't functioning properly:
{
string user_input;
cout << "----------------------------------------" <<endl
<< "Text to Morse Mode" << endl
<< "Enter text for conversion : "<<endl;
cin >> user_input;
cout << endl << endl << user_input << " converts to : ";
unsigned int str_lenght;
str_lenght=user_input.size();
cout << endl;
for (i=0;i<str_lenght;i++)
{
find_string=0;
while (find_string < stop_string)
{
if (user_input[i]==text[find_string][0])
{
count=1;
cout << morse[find_string] << " ";
break;
}
find_string = find_string+1;
}
}
cout << endl << endl << endl;
if (count==0)
cout << endl << " an error was encountered " << "\a" << endl ;
}
stop_string isn't defined anywhere from what I see. In order to break the loop via incrementing you need to define stop_string. Also find_string = find_string+1; could be shortened to find_string++
First you haven't defined stop_string variable anywhere. First define it or use another variable. If it is string length intent to use here, use the str_length you have created.
Secondly if you want to input spaces in between your words, use getline instead of cin. cin delimits space character.