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.
Related
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;
}
}
When I run one file, it works perfectly. Then I separate 3 file: header, main, function from that file. It aslo works but return nothing. Here the code:
File Header: printStudent.h
//Header.h
#ifndef PRINTSTUDENT_H_INCLUDED
#define PRINTSTUDENT_H_INCLUDED
void read ();
#endif
File Function: readFileCSV.cpp . It read and print from my .csv file
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string.h>
#include <algorithm>
#define student 1000
using namespace std;
void read (){
ifstream readFileCSV;
readFileCSV.open("studentEn.csv");
if(!readFileCSV.is_open()) {cout << "ERROR: File can't be opened or it doesn't exist" << endl;};
string aMSSV[student];
string aname[student];
string abirthDay[student];
string aaddress[student];
string MSSV;
string name;
string birthDay;
string address;
int countStudent = 0;
while(readFileCSV.good()) {
getline(readFileCSV, MSSV, ',');
getline(readFileCSV, name, ',');
getline(readFileCSV, birthDay, ',');
getline(readFileCSV, address, '\n');
int lengthAddress = address.length();
char charAddress[lengthAddress];
strcpy(charAddress, address.c_str());
char newCharAddress[lengthAddress-2];
for(int i = 0 ; i < lengthAddress-2 ; i++){
newCharAddress[i] = charAddress[i+1];};
string address(newCharAddress, lengthAddress - 2);
aMSSV[countStudent] = MSSV;
aname[countStudent] = name;
abirthDay[countStudent] = birthDay;
aaddress[countStudent] = address;
countStudent ++;
};
countStudent = countStudent - 1;
cout << "..................................................STUDENT..........................................................." << endl;
cout << setw(5) << left << "STT";
cout << setw(25) << left << "MSSV";
cout << setw(25) << left << "Name";
cout << setw(25) << left << "Date of Birth";
cout << left << "Address";
cout << endl;
cout << "...................................................................................................................." << endl;
for(int i = 0 ; i < countStudent ; i++){
cout << setw(5) << left << i + 1;
cout << setw(25) << left << aMSSV[i];
cout << setw(25) << left << aname[i];
cout << setw(25) << left << abirthDay[i];
cout << left << aaddress[i];
cout << endl;
}
readFileCSV.close();
}
File main:
#include <iostream>
#include "printStudent.h"
using namespace std;
int main(){
void read ();
return 0;
}
Help me why it's return nothing and give me a solution how can i make it works? Thanks!
int main(){
void read ();
return 0;
}
It is a function declaration in main a.k.a. forward declaration. Any expression that starts with a type or void is a declaration. It is a local declaration, thus it doesn't conflict with the globally declared function read.
To call the function do it so
int main(){
read ();
return 0;
}
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;
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;
}
}
code in strfile.cpp:
#include <fstream>
#include <iostream>
#include <assert.h>
#define SZ 100
using namespace std;
int main(){
char buf[SZ];
{
ifstream in("strfile.cpp");
assert(in);
ofstream out("strfile.out");
assert(out);
int i = 1;
while(!in.eof()){
if(in.get(buf, SZ))
int a = in.get();
else{
cout << buf << endl;
out << i++ << ": " << buf << endl;
continue;
}
cout << buf << endl;
out << i++ << ": " << buf << endl;
}
}
return 0;
}
I want to operate all file
but in strfile.out:
1: #include <fstream>
2: #include <iostream>
3: #include <assert.h>
4: ...(many empty line)
I know that fstream.getline(char*, int) this function can manage it,but I want to know how to do this just use the function "fstream.get()".
Because ifstream::get(char*,streamsize) will leave the delimiter (in this case \n) on the stream, your call never advances and thus it appears to your calling program that you are endlessly reading blank lines.
Instead you need to determine if a newline is waiting on the stream, and move past it using in.get() or in.ignore(1):
ifstream in("strfile.cpp");
ofstream out("strfile.out");
int i = 1;
out << i << ": ";
while (in.good()) {
if (in.peek() == '\n') {
// in.get(buf, SZ) won't read newlines
in.get();
out << endl << i++ << ": ";
} else {
in.get(buf, SZ);
out << buf; // we only output the buffer contents, no newline
}
}
// output the hanging \n
out << endl;
in.close();
out.close();