Can someone please tell me why this code doesnt print anything? - c++

I have to write a code that compares three text files and i cant for the life of me find out why this wont print anything:
#include <iostream>
#include <cstring>
#include <string>
#include <fstream>
using namespace std;
int main (int argc, char *argv[])
{
ifstream mousefile;
mousefile.open(argv[1]);
string mouse_dna;
getline(mousefile, mouse_dna);
ifstream humanfile;
humanfile.open(argv[2]);
string human_dna;
getline(humanfile, human_dna);
ifstream unknownfile;
unknownfile.open(argv[3]);
string unknown_dna;
getline(unknownfile, unknown_dna);
int len = mouse_dna.size();
int mouseDistance = 0, humanDistance = 0;
for(int i=0; i<len; i++)
if(mouse_dna[i] != unknown_dna[i])
mouseDistance++;
return mouseDistance;
for(int i=0; i<len; i++)
if(human_dna[i] != unknown_dna[i])
humanDistance++;
return humanDistance;
double similarity_scoreH = (len - humanDistance) / len;
double similarity_scoreM = (len - mouseDistance) / len;
cout << "MouseCompare = " << similarity_scoreM << endl;
cout << "HumanCompare = " << similarity_scoreH << endl;
if (similarity_scoreH == similarity_scoreM)
cout << "identity cannot be determined" << endl;
else if (similarity_scoreH > similarity_scoreM)
cout << "human" << endl;
else if (similarity_scoreM > similarity_scoreH)
cout << "mouse" << endl;
}
It compiles properly, and doesn't give any errors, but when i rut it as:
./DNA mouseDNA.txt humanDNA.txt unknownDNA.txt
it still does nothing.
I appreciate any help. Thanks!

It doesn't print anything because it's returning before the instructions to print (return mouseDistance; or return humanDistance;). Make your function more verbose by printing progress messsages before each return statement.

As already has pointed out, you return too early. I modify your code:
I put brackets around the if block and for block.
I have a return statement at the end.
This is a start. You may have to add more checking, for example, if the file is open correctly.
#include <iostream>
#include <cstring>
#include <string>
#include <fstream>
using namespace std;
int main (int argc, char *argv[])
{
ifstream mousefile;
mousefile.open(argv[1]);
string mouse_dna;
getline(mousefile, mouse_dna);
ifstream humanfile;
humanfile.open(argv[2]);
string human_dna;
getline(humanfile, human_dna);
ifstream unknownfile;
unknownfile.open(argv[3]);
string unknown_dna;
getline(unknownfile, unknown_dna);
int len = mouse_dna.size();
int mouseDistance = 0, humanDistance = 0;
for(int i=0; i<len; i++)
{
if(mouse_dna[i] != unknown_dna[i])
{
mouseDistance++;
}
}
for(int i=0; i<len; i++)
{
if(human_dna[i] != unknown_dna[i])
{
humanDistance++;
}
}
double similarity_scoreH = (len - humanDistance) / len;
double similarity_scoreM = (len - mouseDistance) / len;
cout << "MouseCompare = " << similarity_scoreM << endl;
cout << "HumanCompare = " << similarity_scoreH << endl;
if (similarity_scoreH == similarity_scoreM)
cout << "identity cannot be determined" << endl;
else if (similarity_scoreH > similarity_scoreM)
cout << "human" << endl;
else if (similarity_scoreM > similarity_scoreH)
cout << "mouse" << endl;
return 0;
}

You use arg[1], arg[2], and arg[3]. You may want arg[0], arg[1], and arg[2].

Related

How to read more than one line of input?

So I have built a small basic data encrypter (for learning purposes only). It is working perfectly fine but it reads only a single line of input. Is it my Editor problem or my code have some issues.
ps: I use CodeBlocks
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
std::string str;
char enc;
int word;
cout << "\t\t\t\t\t\t\t\tENCRYPTOR" <<endl;
cout << "\t\t\t\t\t\t\t\t---------" <<endl;
cout << "Enter a Word: ";
getline(cin, str);
int n = 0;
cout << "\n\n\t\t\t\t\t\t\t\tENCRYPTED D#T#" <<endl;
cout << "\t\t\t\t\t\t\t\t--------------\n\n" << endl;
for(int i = 0; i < str.length(); i++){
int randomAdd[5] = {5,6,2,3,2};
int size = sizeof(randomAdd)/sizeof(randomAdd[0]);
// for(int j = 0; j < 5; j++){
word = str.at(i);
if(i%5 == 0){
n = 0;
}
enc = int(word) + randomAdd[n];
std::cout << char(enc);
n++;
}
return 0;
}
This works
Hello World
But I cannot enter this
Hello World
Have a nice day
because then the program exits command prompt without any error or message.
How can I read more than one line?
You can do as
#include <iostream>
using namespace std;
int main() {
string str;
while (getline(cin, str)) {
cout << str << endl;
}
return 0;
}
This code sample allows you to input multiple lines interactively from the command line/shell
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str;
char enc;
int word;
vector<string> myInput;
cout << "\t\t\t\t\t\t\t\tENCRYPTOR" <<endl;
cout << "\t\t\t\t\t\t\t\t---------" <<endl;
while (str != "Enigma")
{
cout << "Enter a line (Write Enigma to exit input): ";
getline(cin, str);
myInput.push_back(str);
}
int n = 0;
cout << "\n\n\t\t\t\t\t\t\t\tENCRYPTED D#T#" <<endl;
cout << "\t\t\t\t\t\t\t\t--------------\n\n" << endl;
for(auto & myInputLine : myInput)
{
str = myInputLine;
for (size_t i = 0; i < str.length(); i++) {
int randomAdd[5] = { 5,6,2,3,2 };
int size = sizeof(randomAdd) / sizeof(randomAdd[0]);
word = str.at(i);
if (i % 5 == 0) {
n = 0;
}
enc = int(word) + randomAdd[n];
std::cout << char(enc);
n++;
}
}
return 0;
}
The input is finished if Enigma is written.
All input is stored in the vector container of the STL, see vector.
Afterwards, all the lines are encrypted by your algorithm.
Hope it helps?

s.erase is not working when trying to remove spaces from a string

I am trying to remove the spaces from a string to validate a Palindrome phrase. I have looked up other methods, but my professor literally copy and pasted the remove space for loop in our instructions but I can't get it to work and he says he doesn't want us going to the internet for help. I am trying to remove spaces from a phrase like "too hot to hoot" to validate it. I can get my program to work with single words like "bob", but not phrases.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char input[100];
cout << "Please enter a word/phrase: ";
cin >> input;
for (int i = 0; i < strlen(input); i++)
{
while (s[i] == ' ')//getting "s" is undefined error
s.erase(i,1);
}
int i = 0;
int j = strlen(input)-1;
bool a = true;
for (i = 0; i < j; i++)
{
if (input[i] != input[j])
{
a = false;
}
j--;
}
if(a)
{
cout << input << " is a Valid Palindrome." << endl;
}
else
{
cout<< input << " is not a Valid Palindrome." << endl;
}
system("pause");
return 0;
}
Maybe you have not copy the result from temporary variable 's'. So, the modified codes should be:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <cstring>
using namespace std;
int main(int argc, char *argv[])
{
char input[100];
cout << "Please enter a word/phrase: ";
fgets(input, 100, stdin);
string s(input); // define a temporary variable 's'
int i = 0;
while (i < s.length())
{
if (s[i] == ' ' || s[i] == '\n')
{
s.erase(i, 1); // erase from variable 's', other then 'input'
continue;
}
i++;
}
// copy result from 's' to 'input'
sprintf(input, "%s", s.c_str());
int j = strlen(input) - 1;
bool a = true;
i = 0;
for (i = 0; i < j; i++)
{
if (input[i] != input[j])
{
a = false;
}
j--;
}
if (a)
{
cout << input << " is a Valid Palindrome." << endl;
}
else
{
cout << input << " is not a Valid Palindrome." << endl;
}
system("pause");
return 0;
}

C++ code crashes instantly due to memory issues

This code should read a .pnm file. I tried to run it with 2 resolutions:
200x200 px: Here everything works just fine.
500x281 px: Code instantly crashes, raising a SIGSEGV error.
As far as I know, SIGSEGV is related to memory issues. I have 8GB of RAM, a quantity that I judge to be enough to run this. I don't have any idea about why it's happening and how to fix it.
Code
#define IO_ERROR (5)
#define X_DIMENSION (500)
#define Y_DIMENSION (281)
#define C_DIMENSION (3)
#define HEADER_SIZE (3)
#define BODY_SIZE (X_DIMENSION * Y_DIMENSION * C_DIMENSION)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int readImage(string fileName, string *imgHeader, string *imgBody)
{
ifstream inputFile(fileName);
if (!inputFile.is_open())
return IO_ERROR;
string line;
int count = 0;
while (getline(inputFile, line)) {
if (line.find("#") != string::npos)
continue;
if (count < 3)
imgHeader[count] = line;
else
imgBody[count - HEADER_SIZE] = line;
count++;
}
inputFile.close();
return 0;
}
void numericParser(const string *imgBody, unsigned char *numericBody)
{
int i = 0;
while(i < BODY_SIZE) {
numericBody[i] = (unsigned) atoi(imgBody[i].c_str());
i++;
}
}
void rgbParser(const string *imgBody, unsigned char rgbMatrix[X_DIMENSION][Y_DIMENSION][C_DIMENSION])
{
unsigned char numericBody[BODY_SIZE];
numericParser(imgBody, numericBody);
int k = 0;
for (int i = 0; i < X_DIMENSION; i++) {
for (int j = 0; j < Y_DIMENSION; j++) {
for (int c = 0; c < 3; c++) {
rgbMatrix[i][j][c] = numericBody[k];
k++;
}
}
}
}
void printInfo(const string *header, const string *body)
{
cout << "#-*- Image Header -*-" << endl;
for (int i = 0; i < HEADER_SIZE; i++) {
cout << header[i] << endl;
}
cout << "#-*- Image Body -*-";
for (int i = 0; i < 5 * C_DIMENSION; i++) {
if (i % 3 == 0) cout << endl << "R: " << body[i];
else if (i % 3 == 1) cout << " G: " << body[i];
else cout << " B: " << body[i];
}
cout << endl << ". . ." << endl;
}
int main()
{
string fileName;
cout << "File name: ";
cin >> fileName;
string imgHeader[HEADER_SIZE];
string imgBody[BODY_SIZE];
if(readImage(fileName, imgHeader, imgBody) == IO_ERROR)
return IO_ERROR;
// printInfo(imageData);
unsigned char rgbMatrix[X_DIMENSION][Y_DIMENSION][C_DIMENSION];
rgbParser(imgBody, rgbMatrix);
return 0;
}
Additional Info
I'm on Arch Linux 64-bit, using CLion as IDE.

Count number of occurrences in string c++?

I'm used to java, and struggle with basic syntax of C++ despite knowing theory. I have a function that is trying to count the number of occurrences in a string, but the output is a tab bit weird.
Here is my code:
#include <cstdlib>
#include <iostream>
#include <cstring>
/*
main
* Start
* prompt user to enter string
* call function
* stop
*
* count
* start
* loop chars
* count charts
* print result
* stop
*/
using namespace std;
void count(const char s[], int counts[]);
int main(int argc, char** argv) {
int counts[26];
char s[80];
//Enter a string of characters
cout << "Enter a string: "; // i.e. any phrase
cin.getline(s,80);
cout << "You entered " << s << endl;
count(s,counts);
//display the results
for (int i = 0; i < 26; i++)
if (counts[i] > 0)
cout << (char)(i + 'a') << ": " << counts[i] << "Times " << endl;
return 0;
}
void count(const char s[], int counts[]){
for (int i = 0; i < strlen(s); i++)
{
char c = tolower(s[i]);
if (isalpha(c))
counts[c - 'a']++;
}
}
Here is the output:
Enter a string: Dylan
You entered Dylan
b: 1Times
c: 1Times
d: 2Times
f: 1Times
h: 1Times
i: 1229148993Times
j: 73Times
l: 2Times
n: 2Times
p: 1Times
r: 1Times
v: 1Times
Any help you can give me would be greatly appreciated. Even though this is simple stuff, I'm a java sucker. -_-
Your counts is uninitialized. You need to first set all of the elements to 0.
You need to zeros the counts vector.
Try
counts[26]={0};
I don't know about java, but you have to initialize your variables in C/C++. Here is your code working:
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;
void count(const char s[], int counts[]){
for (int i = 0; i < strlen(s); i++)
{
char c = tolower(s[i]);
if (isalpha(c))
counts[c - 'a']++;
}
}
int main(int argc, char** argv) {
int counts[26];
char s[80];
//Enter a string of characters
cout << "Enter a string: "; // i.e. any phrase
cin.getline(s,80);
for(int i=0; i<26; i++)
counts[i]=0;
cout << "You entered " << s << endl;
count(s,counts);
//display the results
for (int i = 0; i < 26; i++)
if (counts[i] > 0)
cout << (char)(i + 'a') << ": " << counts[i] << "Times " << endl;
return 0;
}

Confused about taking file name from command line and stuff to it C++

My problem is that I cant get the getting the filename from the command line from the user, then using that filename to write the median, mode, and average. Im new to c++ so any tips or code fix would be great, and if you guys see anything else wrong please let me know, this is what I have, Im 99% done with it its just this filewriting thats giving me problems. Thank you
#include <iostream>
#include <fsteam>
#include <string>
using namespace std;
double Median(int [], int);
double Average(int [], int);
double Mode(int [], int);
int main(int argc, char *argv[])
{
ofstream outFile;
string filename = argv[1];
outputFile.open(filename.c_str());
if(!outFile)
{
cerr << "Error with the file.";
}
else
{
continue;
}
int *array;
int array_size;
cout << "How many students were surveyed? " << endl;
cin >> array_size;
if(array_size < 1)
{
cout << "Number of students surveyed must be greater than 1." << endl;
return(1);
}
else
{
array = new int [array_size];
}
cout << "Enter the number of movies each studen saw." << endl;
for(int i = 0; i < array_size; i++)
{
cout << "Student " << i+1 << ": " << endl;
cin >> array[i];
}
for(int i = 0; i < array_size; i++)
{
for(int j = i+1; j < array_size-1; j++)
{
if(array[i] > array[j])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
double median = Median(array, array_size);
double average = Average(array, array_size);
double mode = Mode(array, array_size);
outFile << "Median: " << median << endl;
outFile << "Average: "<< average << endl;
outFile << "Mode: " << mode << endl;
return 0;
}
double Median(int arr[], int size)
{
double middle;
if(size%2 == 0)
middle = (arr[size/2] + arr[size/2-1])/2;
else
middle = arr[size/2];
return middle;
}
double Average(int arr[], int size)
{
double ave = 0;
for(int i = 0; i < size ; i++)
ave += arr[i];
ave = ave/size;
return ave;
}
double Mode(int arr[], int size)
{
int count, mode = 0;
for(int i = 0; i < size; i++)
{
count = 1;
while(arr[i] == arr[i+1])
{
count++;
i++;
}
if(count > mode)
mode = arr[i];
if(count > 1)
i--;
}
return mode;
}
You'll likely see something about this in the compiler, but I'll let you know anyways #include <fsteam> is <fstream>
I'm confused as to why you chose to put this
else
{
continue;
}
instead of nothing, since continue; just jumps to the end of the current iteration, which doesn't seem necessary here.
The rest of it seems fine. It's formatted to be easily read. If you have any errors post-testing, let me know.
EDIT: Sorry, I can't add comments yet, but in response to your comment, it's likely because of what I noted about <fstream> above. It's just a typo.
I tried it with following patch.
--- orig.cpp 2014-05-17 12:39:37.000000000 +0800
+++ new.cpp 2014-05-17 12:38:28.000000000 +0800
## -1,5 +1,5 ##
#include <iostream>
-#include <fsteam>
+#include <fstream>
#include <string>
using namespace std;
## -16,13 +16,13 ##
outputFile.open(filename.c_str());
- if(!outFile)
+ if(!outputFile)
{
cerr << "Error with the file.";
}
else
{
- continue;
+// continue;
}
## -64,9 +64,9 ##
double median = Median(array, array_size);
double average = Average(array, array_size);
double mode = Mode(array, array_size);
- outFile << "Median: " << median << endl;
- outFile << "Average: "<< average << endl;
- outFile << "Mode: " << mode << endl;
+ outputFile << "Median: " << median << endl;
+ outputFile << "Average: "<< average << endl;
+ outputFile << "Mode: " << mode << endl;
return 0;
}
I think that as following.
first, You type incorrectly with fsteam -> fstream.
second, you type incorrectly with outFile -> outputFile.
third, you must don't use continue without loop.
As result, I suggest you have more focus about typing error.
Better to check the count command line arguments.
int main(int argc, char *argv[])
{
if(argc <2 )
{
cout << "Specify out file name as command line argument";
return 0;
}
. . . . .
. . . . .
}
for more details,
http://www.cprogramming.com/tutorial/c/lesson14.html