Placing Printed text in the same line as text before it - c++

I'm currently making a basic program design to behave somewhat like a chell. The code is here:
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <Windows.h>
#include <Stdio.h>
#include <string>
using namespace std;
main()
{
SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE),10);
std::string name;
std::string pass;
std::string msg;
int x = 1;
srand(time(0));
cout << "Booting up system..." << endl;
cout << "Serial Code: " << (rand()%1000) << "." << endl;
cout << "Username: ";
std::getline(std::cin, name);
cout << "Password: ";
std::getline(std::cin, pass);
cout << "" << endl;
while (true)
{
cout<<x<<": ";
std::getline(std::cin, msg);
x += 1;
if (msg == "Hello!"){
cout << "Hi!" << endl;
}
if (msg == ""){
cout << "[No Text Inserted]" << endl;
}
system ("pause");
}
And, if no text is input it displays:
1:
[No Text Inserted]
How do I get this output?
1: [No Text Inserted]
Thank you in advance!
-DJ

In your if statements, store the string into a variable and print out in the end. Also if you're comparing the same variable, I recommend using if else statements. It makes it more readable. So:
string output;
if (msg == "Hello!)
{
output = "Hi!";
}
else if (msg == "")
{
output = "[No Text Inserted]";
}
output = x.str() + ": " + output;
cout << output << endl;
Try that out and let me know if that works.

What you could do is remember input cursor position and if the input is empty string, go back to that position and print your fail message, something like this:
#include <iostream>
#include <string>
#include <windows.h>
int main()
{
HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
std::string input;
std::cout << "Enter something: ";
// remember cursor position
CONSOLE_SCREEN_BUFFER_INFO info;
COORD inputPos = GetConsoleScreenBufferInfo(conout, &info) ? info.dwCursorPosition : COORD{ 0, 0 };
if (!std::getline(std::cin, input) || input.empty())
{
SetConsoleCursorPosition(conout, inputPos);
std::cout << "[No Text Inserted]" << std::endl;
}
}

Related

Getting stockfish running as child process in C++

I am currently trying to run simple tests with the Stockfish chess engine in C++ to get the best possible move. I am starting Stockfish as a child process and want to use the input and output streams to pass on the desired UCI commands, which I am exchanging with the parent process via a pipe. However, when I run the code, Stockfish just starts and nothing else happens. Typing in the UCI commands in the CLI then works, but that's obviously not the goal. What am I doing wrong?
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
void sig_handler(int sig) {}
int main() {
int fd1[2];
if (pipe(fd1) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
int pid = fork();
if (pid == 0) {
execl("./stockfish", "./stockfish", nullptr);
close(fd1[1]);
char position[60];
read(fd1[0], position, 60);
close(fd1[0]);
cout << "position " << position << endl;
cout << "go" << endl;
sleep(5000);
cout << "stop" << endl;
string move;
cin >> move;
exit(0);
}
else {
close(fd1[0]);
cout << "Parent process" << endl;
string line = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
write(fd1[1], line.c_str(), strlen(line.c_str()) + 1);
close(fd1[1]);
signal(SIGINT, &sig_handler);
wait(NULL);
cout << "Parent done" << endl;
}
return 0;
}
Thanks to #TedLyngmo and some research about the Boost library, it was very easy to implement:
#include <boost/process.hpp>
#include <boost/asio.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
using namespace std;
namespace bp = boost::process;
int main() {
bp::ipstream is;
bp::opstream os;
bp::child c("./stockfish", bp::std_in < os, bp::std_out > is);
os << "uci" << endl;
os << "isready" << endl;
os << "position fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" << endl;
os << "go depth 30" << endl;
string line;
string move_string;
while (getline(is, line)) {
if (!line.compare(0, 8, "bestmove")) {
move_string = line;
break;
}
}
// Delete the "bestmove" part of the string and get rid of any trailing characters divided by space
move_string = move_string.substr(9, move_string.size()-9);
vector<string> mv;
boost::split(mv, move_string, boost::is_any_of(" "));
cout << "Stockfish move: " << mv.at(0) << endl;
return 0;
}

Floating Point Exception while reading from file

the program should read from 2 files (author.dat and citation.dat) and save them into a map and set;
first it reads the citationlist without problem, then it seems to properly read the authors and after it went through the whole list (author.dat) a floating point exception arises .. can't quite figure out why
seems to happen in author.cpp inside the constructor for authorlist
author.cpp:
#include <fstream>
#include <iostream>
#include "authors.h"
using namespace std;
AuthorList::AuthorList(char *fileName) {
ifstream s (fileName);
int idTemp;
int nrTemp;
string nameTemp;
try {
while (true){
s >> idTemp >> nrTemp >> nameTemp;
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
if (!s){
cout << "IF-CLAUSE";
throw EOFException();
}
cout << "WHILE-LOOP_END" << endl;
}
} catch (EOFException){}
}
author.h:
#ifndef CPP_AUTHORS_H
#define CPP_AUTHORS_H
#include <iostream>
#include <map>
#include <string>
#include "citations.h"
class Author {
public:
Author (int id, int nr, std::string name) :
articleID(id),
authorNR(nr),
authorName(name){}
int getArticleID() const {
return articleID;
}
std::string getAuthorName() const {
return authorName;
}
private:
int articleID;
int authorNR;
std::string authorName;
};
class AuthorList {
public:
AuthorList(char *fileName);
std::pair<std::multimap<int,Author>::const_iterator, std::multimap<int,Author>::const_iterator> findAuthors(int articleID) {
return authors.equal_range(articleID);
}
private:
std::multimap<int,Author> authors;
};
#endif //CPP_AUTHORS_H
programm.cpp:
#include <iostream>
#include <cstdlib>
#include "citations.h"
#include "authors.h"
#include "authorCitation.h"
using namespace std;
int main(int argc, char *argv[]){
CitationList *cl;
AuthorList *al;
//check if argv array has its supposed length
if (argc != 4){
cerr << "usage: programm article.dat citation.dat author.dat";
return EXIT_FAILURE;
}
//inserting citation.dat and author.dat in corresponding lists (article.dat not used)
cl = new CitationList(argv[2]);
al = new AuthorList(argv[3]);
try {
AuthorCitationList *acl;
acl->createAuthorCitationList(al,cl);
acl->printAuthorCitationList2File("authorcitation.dat");
} catch (EOFException){
cerr << "something went wrong while writing to file";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
All files:
https://drive.google.com/file/d/0B734gx5Q_mVAV0xWRG1KX0JuYW8/view?usp=sharing
I am willing to bet that the problem is caused by the following lines of code:
AuthorCitationList *acl;
acl->createAuthorCitationList(al,cl);
You are calling a member function using an uninitialized pointer. I suggest changing the first line to:
AuthorCitationList *acl = new AuthorCitationList;
Add any necessary arguments to the constructor.
While you are at it, change the loop for reading the data also. You have:
while (true){
s >> idTemp >> nrTemp >> nameTemp;
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
if (!s){
cout << "IF-CLAUSE";
throw EOFException();
}
cout << "WHILE-LOOP_END" << endl;
}
When you do that, you end up adding data once after the end of line has been reached. Also, you seem to have the last line in the wrong place. It seems to me that it should be outside the while loop.
You can use:
while (true){
s >> idTemp >> nrTemp >> nameTemp;
// Break out of the loop when reading the
// data is not successful.
if (!s){
cout << "IF-CLAUSE";
throw EOFException();
}
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
}
cout << "WHILE-LOOP_END" << endl;
You can simplify it further by using:
while (s >> idTemp >> nrTemp >> nameTemp){
cout << idTemp << " " << nrTemp << " " << nameTemp << " test_string";
authors.insert(std::make_pair(idTemp,Author(idTemp,nrTemp,nameTemp)));
}
cout << "WHILE-LOOP_END" << endl;

Function not recognized within scope

I've almost finished writing a program that will detect palindromes from a file and output a new file highlighting the palindromes but I'm stuck on a really dumb error. I'm trying to write a test for one of my methods (TDD) and, for some reason, it's not recognizing the function as within the scope.
I'm calling the isPalindrome(string s) method (declared in PalindromeDetector.h) in my isPalindromeTest() method (declared in PalindromeDetectorTest.h) but, for some reason, it's not recognizing it as within the scoope.
I feel like everything should be working but it just isn't. Any help you can provide would be greatly appreciated. Below is my code:
PalindromeDetector.h
#ifndef PALINDROMEDETECTOR_H_
#define PALINDROMEDETECTOR_H_
#include <iostream>
using namespace std;
class PalindromeDetector {
public:
void detectPalindromes();
bool isPalindrome(string s);
};
#endif /* PALINDROMEDETECTOR_H_ */
PalindromeDetector.cpp
#include "PalindromeDetector.h"
#include "Stack.h"
#include "ArrayQueue.h"
#include <iostream>
#include <fstream>
#include <cassert>
#include <cctype>
#include <string>
using namespace std;
void PalindromeDetector::detectPalindromes() {
cout << "Enter the name of the file whose palindromes you would like to detect:" << flush;
string fileName;
cin >> fileName;
cout << "Enter the name of the file you would like to write the results to: " << flush;
string outFileName;
cin >> outFileName;
fstream in;
in.open(fileName.c_str());
assert(in.is_open());
ofstream out;
out.open(outFileName.c_str());
assert(out.is_open());
string line;
while(in.good()){
getline(in, line);
line = line.erase(line.length()-1);
if(line.find_first_not_of(" \t\v\r\n")){
string blankLine = line + "\n";
out << blankLine;
} else if(isPalindrome(line)){
string palindromeYes = line + " ***\n";
out << palindromeYes;
} else {
string palindromeNo = line + "\n";
out << palindromeNo;
}
if(in.eof()){
break;
}
}
in.close();
out.close();
}
bool PalindromeDetector::isPalindrome(string s){
unsigned i = 0;
Stack<char> s1(1);
ArrayQueue<char> q1(1);
while(s[i]){
char c = tolower(s[i]);
if(isalnum(c)){
try{
s1.push(c);
q1.append(c);
} catch(StackException& se) {
unsigned capS = s1.getCapacity();
unsigned capQ = q1.getCapacity();
s1.setCapacity(2*capS);
q1.setCapacity(2*capQ);
s1.push(c);
q1.append(c);
}
}
i++;
}
while(s1.getSize() != 0){
char ch1 = s1.pop();
char ch2 = q1.remove();
if(ch1 != ch2){
return false;
}
}
return true;
}
PalindromeDetectorTest.h
#ifndef PALINDROMEDETECTORTEST_H_
#define PALINDROMEDETECTORTEST_H_
#include "PalindromeDetector.h"
class PalindromeDetectorTest {
public:
void runTests();
void detectPalindromesTest();
void isPalindromeTest();
};
#endif /* PALINDROMEDETECTORTEST_H_ */
PalindromeDetectorTest.cpp
#include "PalindromeDetectorTest.h"
#include <cassert>
#include <iostream>
#include <fstream>
#include <cctype>
#include <string>
using namespace std;
void PalindromeDetectorTest::runTests(){
cout << "Testing palindrome methods... " << endl;
detectPalindromesTest();
isPalindromeTest();
cout << "All tests passed!\n" << endl;
}
void PalindromeDetectorTest::detectPalindromesTest(){
cout << "- testing detectPalindromes()... " << flush;
fstream in;
string fileName = "testFile.txt";
in.open(fileName.c_str());
assert(in.is_open());
cout << " 1 " << flush;
ofstream out;
string fileOutName = "testFileOut.txt";
out.open(fileOutName.c_str());
assert(out.is_open());
cout << " 2 " << flush;
cout << " Passed!" << endl;
}
void PalindromeDetectorTest::isPalindromeTest(){
cout << "- testing isPalindrome()... " << flush;
// test with one word palindrome
string s1 = "racecar";
assert(isPalindrome(s1) == true); // these are not recognized within the scope
cout << " 1 " << flush;
// test with one word non-palindrome
string s2 = "hello";
assert(isPalindrome(s2) == false); // these are not recognized within the scope
cout << " 2 " << flush;
// test with sentence palindrome
string s3 = "O gnats, tango!";
assert(isPalindrome(s3) == true); // these are not recognized within the scope
cout << " 3 " << flush;
// test with sentence non-palindrome
string s4 = "This is not a palindrome.";
assert(isPalindrome(s4) == false); // these are not recognized within the scope
cout << " 4 " << flush;
cout << " Passed!" << endl;
}
isPalindrome is a member function of PalindromeDetector, but you are trying to call it from within a PalindromeDetectorTest method. If the test class derived from PalindromeDetector this would work, but there isn't (and almost certainly shouldn't be) any such relationship between them.
You need a PalindromeDetector object to call the method on. Probably just as simple as this:
void PalindromeDetectorTest::isPalindromeTest(){
cout << "- testing isPalindrome()... " << flush;
PalindromeDetector sut; // "subject under test"
// test with one word palindrome
string s1 = "racecar";
assert(sut.isPalindrome(s1) == true);
// etc.
}
You could also make the PalindromeDetector methods static since the object doesn't appear to have any state. Then you could simply call PalindromeDetector::isPalindrome(s1); without the need to create an instance.

having issues comparing strings

For some reason it skips over the first input an goes straight to the second one.
#include<iostream>
#include<string>
using namespace std;
int stringWork()
{
const int LENGTH = 40;
char firstString[LENGTH], secondString[LENGTH];
cout << "Enter First String: ";
//it skips over this following line
cin.getline(firstString, LENGTH);
cout << "Enter Another String: ";
cin.getline(secondString, LENGTH);
if (strcmp(firstString, secondString) == 0)
cout << "You entered Same string two times\n";
else
cout << "The two strings you entered are not the same\n";
system("pause");
return 0;
}
int main()
{
stringWork();
return 0;
}
it only allows input for one string
This piece of code works on my machine just fine. However, please do change #include <string> to #include <string.h> or #include <cstring>, and add #include <stdlib.h> or #include <cstdlib>.
Fix the code like this:
#include <iostream>
#include <string>
void stringWork()
{
const int LENGTH = 40;
char firstString[LENGTH], secondString[LENGTH];
std::cout << "Enter First String: " << std::flush;
std::cin.getline(firstString, LENGTH);
std::cout << "Enter Another String: " << std::flush;
std::cin.getline(secondString, LENGTH);
if (strcmp(firstString, secondString) == 0) {
std::cout << "You entered Same string two times." << std::endl;
} else {
std::cout << "The two strings you entered are not the same." << std::endl;
}
}
int main()
{
stringWork();
return 0;
}
Some notes about my version of your code:
Please don't use using namespace std.
Use std::flush to flush the characters in the output stream. This is necessary because usually the characters are only flushed with std::endl or in some implementations if you add a newline character.
Avoid mixing C and C++ code as you did. Use the std::getline method to read a line directly into a std::string. Shown in the next example.
Please care about your code style, especially if you post it in the public.
A even better implementation would avoid any C code and use just C++:
#include <iostream>
#include <string>
void stringWork()
{
std::cout << "Enter First String: " << std::flush;
std::string firstString;
std::getline(std::cin, firstString);
std::cout << "Enter Another String: " << std::flush;
std::string secondString;
std::getline(std::cin, secondString);
if (firstString == secondString) {
std::cout << "You entered Same string two times." << std::endl;
} else {
std::cout << "The two strings you entered are not the same." << std::endl;
}
}

Dev-C++ 4.9.9.2 Basic Program Error

I'm making this program that takes my family member's names and gives out their horoscope. And I'm getting some errors which bugs me. The random names are just for "privacy". And yes I'm just a starter and im working with basic arrays.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
string name;
string hs[4];
hs[0] = "Aquarius";
hs[1] = "Cancer";
hs[2] = "Leo";
hs[3] = "Taurus";
cin >> name;
if name = "Harp"
{
cout << hs[0] << endl;
}
if name = "Herp"
{
cout << hs[1] << endl;
}
if name = "Derp"
{
cout << hs[2] << endl;
}
if name = "Darp"
{
cout << hs[3] << endl;
}
cout << "Press Enter To Exit This Program.";
cin.get();
return 0;
}
I keep getting this:
expected `(' before "name"
Any help would be nice.
Thanks!!
Check out proper if syntax. - missing ( and ).
the corrected program is this. Note the proper syntax of if statement
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
string name;
string hs[4];
hs[0] = "Aquarius";
hs[1] = "Cancer";
hs[2] = "Leo";
hs[3] = "Taurus";
cin >> name;
if (name == "Harp")
{
cout << hs[0] << endl;
}
if (name == "Herp")
{
cout << hs[1] << endl;
}
if (name == "Derp")
{
cout << hs[2] << endl;
}
if (name == "Darp")
{
cout << hs[3] << endl;
}
cout << "Press Enter To Exit This Program.";
cin.get();
return 0;
}
if (name == "Harp")
Pay attention to the ( and ), they are not optional. Also use == (not =, it assing the value in the right side to the left, here name will have change the contenct to "Harp", and then convert it to bool, ...)