When I enter this code and try to run it, it isn't working when the user selects option 1, to enter some text and a string to search for within their text. It outputs "enter text" and then "enter string to search" immediately after, without giving the user the chance to input some text. What is wrong?
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <algorithm>
using namespace std;
string s1, text;
int rand(int*);
int Array[100];
void sortArray(int[], int);
void showArray(const int [], int);
int main()
{
while (1)
// Menu to prompt user choice
{
char choice[1];
cout << endl;
cout << endl;
cout << "--MENU--" << endl;
cout << "1. Pattern Matching" << endl; // search for string within text
cout << "2. Sorting Techniques" << endl; // generate and then sort 10 random numbers
cout << "Enter your choice: " << endl;
cout << endl;
cin >> choice;
cout << endl;
if (choice[0] == '1') // string search option
{
cout << "Enter text:" << endl; // accept text from user
getline (cin, s1);
cout << "Enter string to search:" << endl; // accept string to search from user
getline (cin, text);
int pos = s1.find(text); // finds position where the string is located within text
if (pos >= 0)
{
cout << "Found '" << text << "'" << " at position " << pos + 1 << "." << endl;
}
else
{
cout << "Did not find text." << endl;
}
}
This is because cin >> choice reads part of the current input line for the choice entered by the user. The first getline() call reads the remaining part of the input line immediately following the choice entered by the user. You need to ignore the rest of the input line after the choice.
cin >> choice;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
You will also need to add #include <limits> to the beginning of your code in order to pull in numerical_limits.
It looks as though you are defining some sort of char array for the user response. I would tend to make that a non-zero integer type with an exception if the choice is neither 1 nor 2. There are also some shortcuts for output formatting that reduces lines of code. Also, you would want to include the standard string class to accept the string. Maybe try something like the following:
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <algorithm>
using namespace std;
string s1, text;
int rand(int*);
int Array[100];
void sortArray(int[], int);
void showArray(const int [], int);
int main()
{
while (1)
// Menu to prompt user choice
{
int choice;
cout << "\n--MENU--\n"l;
cout << "1. Pattern Matching\n"; // search for string within text
cout << "2. Sorting Techniques\n"; // generate and then sort 10 random numbers
cout << "Enter your choice:\n";
cin >> choice+"\n";
if (choice == 1 && choice > 0 && choice != 0) // string search option
{
cout << "Enter text:" << endl; // accept text from user
getline (cin, s1);
cout << "Enter string to search:" << endl; // accept string to search from user
getline (cin, text);
int pos = s1.find(text); // finds position where the string is located within text
if (pos >= 0)
{
cout << "Found '" << text << "'" << " at position " << pos + 1 << ".\n";
}
else
{
cout << "Did not find text.\n";
}
}}}
Related
I am having trouble determining if an input is a letter or a number.
If I enter anything it always says that it is not a number, what am I doing wrong.
Here is my code:
#include <iostream>
#include <unistd.h>
#include <ctype.h>
using namespace std;
int main()
{
int input = 0;
cout << "Enter a number \n";
cout << "input: ";
cin >> input;
if (isdigit(input)) {
cout << "Your number is: " << input;
}
else {
cout << "This is not a number \n";
}
//wait for ten seconds
usleep(10000000);
}
Since isdigit() expects an ASCII value as its argument, it will return true only if you type in a number between 48 (aka the ASCII code for "0") and 57 (aka the ASCII code for "9"), which isn't what you want.
In order to get the behavior you want, you'll need to read the user's input into a string, and then analyze the contents of the string to see if they reasonably represent an integer or not. Something like this:
#include <iostream>
#include <string>
#include <unistd.h>
#include <ctype.h>
using namespace std;
int main()
{
string inputStr;
cout << "Enter a number \n";
cout << "input: ";
cin >> inputStr;
// Assume a string counts as representing an integer
// if the first character of the string is an ASCII digit.
// (You might also want to accept strings where the
// first character is a + or - symbol and is immediately
// followed by an ASCII digit, but for simplicity I'm
// omitting that logic here)
if ((inputStr.length()>0)&&((isdigit(inputStr[0])))) {
int number = stoi(inputStr);
cout << "Your number is: " << number << endl;
}
else {
cout << "[" << inputStr << "] is not a number" << endl;
}
//wait for ten seconds
usleep(10000000);
}
Agree on Jeremy, I would like to add https://stackoverflow.com/a/5655685/7637661 for reference.
TLDR
#include <iostream>
using namespace std;
int main() {
int input = 0;
cout << "Enter a number \n";
cout << "input: ";
cin >> input;
if(!cin) // or if(cin.fail())
{
// user didn't input a number
cin.clear(); // reset failbit
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input
// next, request user reinput
cout << "This is not a number " << endl;
}
cout << "Your number is: " << input;
}
I'm trying to write a code for signup / login while being able to write and read from the file. So far I am able to write in the file and asked for the users input and displayed in the file (signup).
My problem is now,
How do I do the login part, in which when the user chooses login, they are able to choose what username they want based on a selection of usernames and the input they have made while choosing the first option?
How can this information be read and displayed in the file?
Expected output for user login
Choose you username:
0:mike
1:Linda
2:Martha
Expected input from the user
your choice: "Key in choice"
So far the code displayed works, but I am not sure what to do for my next step.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
int option;
int age,height;
string name;
string database;
ofstream file_out;
ifstream file_in;
cout << " For sign up type 1" <<endl;
cout << " For log in type 2" <<endl;
cin >> option;
if ( option == 1 ) {
file_out.open("database.txt");
cout << "Input name: \n";
cin >> name;
cout << "Input age: \n";
cin >> age;
cout << " Input height: \n";
cin >> height;
//write file
file_out << name << endl;
file_out << age << endl;
file_out << height << endl;
file_out.close();
} else if (option == 2) {
//read file
file_in.open("database.txt");
cout << "choose your username: " << endl;
// input line of code
while ( getline(file_in, database));
//input line of code
cout << database << endl;
You can do something like this. Print all the usernames, but before printing out check if they are numbers with help of the stof function, if they are numbers we don't have to do anything, but if it is a string it will throw an exception, so in the catch block we print it and store it into dictionary/map for easy retrieval.
#include <fstream>
#include <iostream>
#include <map>
int main(void) {
std::fstream file;
file.open("secret.txt", std::ios::in);
std::map<int, std::string> map;
std::string username;
int count = 1;
while (!file.eof()) {
file >> username;
try {
std::stof(username);
} catch (...) {
std::cout << count << ". " << username << "\n";
map.insert(std::make_pair(count, username));
count++;
}
}
int choice;
std::cout << "Choose your username: ";
std::cin >> choice;
username = map.at(choice);
std::cout << "Your username is set to " << username;
return 0;
}
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//void FillNames(vector<string> & vecNames);
//void SortNames(vector<string> & vecNames);
int main() {
string firstName;
int i = 0;
cout << "Information:" << endl;
cout << "EOF character in windows is Control + Z" << endl;
cout << "and EOF character on Mac is Control + D:" << endl;
cout << "-----------------------------------------------" << endl;
while (i < 13) {
cout << "Enter first name only in all caps (example: JOHN)" << endl;
cout << "Enter EOF character to exit name entry: ";
cin >> firstName;
i++;
}
}
Here is a link to what i'm trying to accomplish.
https://drive.google.com/file/d/1AuW9hQPbd1f294dCZN6Q8Ac6lgIy0Ivf/view?usp=sharing
You can use the stream's input state to break the loop when EOF is entered:
while (i < 13) {
cout << "Enter first name only in all caps (example: JOHN)" << endl;
cout << "Enter EOF character to exit name entry: ";
if (cin >> firstName)
i++;
else
break;
}
Hi im having trouble with an if statement in C++. When I compile my code I get an error stating " no operator "||" matches these operands". Any guesses? The project is a small text based game I'm creating in visual studio.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <fstream>
using namespace std;
//Prototypes
void introScreen(int);
string characterCreation(string);
int choice;
string characterName, wepon1, wepon2, bow, sword, mace;
const string sword = sword;
const string bow = bow;
const string mace = mace;
// Functions
int main()
{
introScreen(choice);
return 0;
}
void introScreen(int choice)
{
cout << "----------------------------------------\n"
<< "Welcome to the arena!\n"
<< "Select a menu option\n"
<< "-----------------------------------------\n"
<< "1. New Game\n"
<< "2. Load\n"
<< "3. Exit\n\n"
<< "Enter your desired number ";
cin >> choice;
if (choice == 1)
characterCreation(characterName);
else
if (choice == 2)
exit(0);
else
if (choice == 3)
exit(1);
}
string characterCreation(string characterName,string wepon1,string wepon2, const string bow, const string sword, const string mace)
{
cout << "Welcome to the character creation menu!\n"
<< "Enter your name\n"
<< "Name: ";
cin.ignore();
getline(cin, characterName);
ofstream loadFile("Save.txt");
loadFile << characterName << endl;
cout << "\nEnter 2 wepons\n"
<< "Wepon list\n\n"
<< "Sword\n"
<< "Mace\n"
<< "Bow\n";
cin >> wepon1, wepon2;
if (wepon1 || wepon2 != bow || sword || mace)
{
cout << "\n\nThose wepons are invalid! Enter new ones\n";
cout << "\nEnter 2 wepons\n"
<< "Wepon list\n\n"
<< "sword\n"
<< "mace\n"
<< "bow\n";
cin >> wepon1, wepon2;
}
loadFile << wepon1 << endl
<< wepon2 << endl;
return characerName;
}
The '||' operator is an evaluation of a logical condition and you are asking it to evaluate a string type. Generally, when strings values are evaluated, they are evaluated as
if (weapon1 != "") then...
Also, be careful about how you set the value. String values are passed inside double quotation marks.
all!
I'm trying to find the best way to accept user input, timestamp it, then place it into a file with correct formatting (One timestamp/input per line. What is the best way to timestamp then give over to put it all in a file? Thanks!
Heres my barebones code as an example:
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
using namespace std;
//void passwordCheck()
//{
//
//}
string timestamp(string passwordInput1, string passwordInput2, string passwordInput3, string passwordInput4, string passwordInput5, string passwordInput6, string passwordInput7, string passwordInput8, string passwordInput9, string passwordInput10)
{
time_t now = time(0);
char* dt = ctime(&now);
cout << "The local date and time is: " << dt << endl;
tm *gmtm = gmtime_s(&now);
dt = asctime(gmtm);
}
//void saveToFile()
//{
//
//cout << "I've saved 10 passwords for you." << endl;
//}
int main()
{
ofstream outputToFile;
outputToFile.open("manageMyPasswords.txt");
// Look for easier/cleaner way to do this.
string passwordInput1, passwordInput2, passwordInput3, passwordInput4, passwordInput5, passwordInput6, passwordInput7, passwordInput8, passwordInput9, passwordInput10;
// Put into a function then call back here.
cout << "Welcome to Password Manager!" << endl;
cout << " Enter your first password" << endl;
getline (cin, passwordInput1);
cout << "Enter the next password." << endl;
getline (cin, passwordInput2);
cout << "Enter the next password." << endl;
getline (cin, passwordInput3);
cout << "Enter the next password." << endl;
getline (cin, passwordInput4);
cout << "Enter the next password." << endl;
getline (cin, passwordInput5);
cout << "Enter the next password." << endl;
getline (cin, passwordInput7);
cout << "Enter the next password." << endl;
getline (cin, passwordInput8);
cout << "Enter the next password." << endl;
getline (cin, passwordInput9);
cout << "Enter the next password." << endl;
getline (cin, passwordInput10);
//void saveToFile();
system("pause");
return 0;
}
As I understood your question you need sth like this:
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <map>
int main(int argc, char** argv)
{
typedef std::multimap<time_t, std::string> Passwords;
Passwords passwords;
short counter = 1;
std::cout << "Enter passwords or \"quit\" to stop" << std::endl;
for (std::string line;;)
{
std::cout << "Enter password " << counter << " -> ";
getline(std::cin, line);
if (line.empty())
{
continue;
}
else if (line.compare("quit") == 0)
{
break;
}
passwords.insert(std::pair<time_t, std::string>(time(0), line));
counter++;
}
std::ofstream outputFile;
outputFile.open("manageMyPasswords.txt", std::ios::trunc);
for (Passwords::const_iterator it = passwords.begin(); it != passwords.end(); it++)
{
outputFile << it->first << " " << it->second << "\n";
}
outputFile.close();
return 0;
}
It will wait for users input infinitely, until "quit" is not entered. After that it will dump timestamps with password line by line.
P.S. I've used multimap, because you can have duplicate timestamps.
Update
It seems from your code that you need human-readable time. Use this function to retrieve current date and time:
// Returns current date-time formatted like [YYYY-MM-DD][HH:mm:ss]
const std::string GetCurrentDateTime()
{
time_t currentTime = time(0);
struct tm localDateTime;
char buf[80];
localtime_s(&localDateTime, ¤tTime);
strftime(buf, sizeof(buf), "[%Y-%m-%d][%X]", &localDateTime);
return buf;
}