I am trying to compile this code please review - c++

using namespace std;
int main()
{
string dna1;
getline(cin, dna1);
string dna2;
getline(cin, dna2);
int hammingDistance=0;
for (int i=0; i < dna1.length(); ++i) {
if (dna1[i] !=dna2[i]) {
hammingDistance++;
}
}
cout <<"HammingDistance is: " << hammingDistance << '\n’;
}
So this is the code I have compiled but it seems to have some error this is from the website Rosalind to which I have added the link below:http://rosalind.info/problems/hamm/

As Michael Roy commented, you're missing the header files you need, iostream and string.
#include <iostream>
#include <string>
You need to format your code though. As it is, it's hard to read, in a regular production-size project, it would be impossible. I also don't recommend using the "using namespace std;" declaration. It's a bad beginner habit to get into.
Everyone has their own specific preferences, but this is roughly what your code should look like.
#include <iostream>
#include <string>
int main()
{
std::string dna1;
std::cin >> dna1;
//getline(cin, dna1);
std::string dna2;
std::cin >> dna2;
//getline(cin, dna2);
int hammingDistance = 0;
for (int i=0; i < dna1.length(); ++i) {
if (dna1[i] != dna2[i]) {
hammingDistance++;
}
}
std::cout <<"HammingDistance is: " << hammingDistance << '\n';
return 0;
}
I used the standard stream methods for input for consistency, but there's nothing technically wrong with other methods, as long as you don't use gets().

Related

Optimize an algorithm to find multiple specific substrings of a string

I'm new to C++ coding and just started solving competitive programming problems. I want to solve the following task: https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1620.
I want to find a substring of a string. The problem is that the code below is slow and I fail the submission by getting the "time limit exceeded" "error". What can I do to speed up the code?
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
stringstream ss;
string m;
char prob[100000];
char substring[1000];
int howManyCases = 0;
int numberOfTests = 0;
cin >> numberOfTests;
cin.ignore();
while(numberOfTests--)
{
cin >> prob >> howManyCases;
while(howManyCases--)
{
cin >> substring;
if (strstr(prob,substring)) {
ss << 'y' << "\n";
}
else
{
ss << 'n' << "\n";
}
}
}
m = ss.str();
cout << m;
return 0;
}
i would make you of <algorithm> header:
std::string parent_string = "some string lala";
std::string sub_string = "lala";
auto found = parent_string.find(sub_string);
it will return iterator to where substring is. Then I wou;d use this clause:
if (found != std::string::npos) std::cout << "y\n";
else std::cout << "n\n";
If there is no limitation to the use of standard libraries, It's always a better choice to use it instead of creating your own algorithms (that may not handle some special cases you won't think of ).
Also, swap those huge ugly c-style arrays to std::string.

How to build a Vector of strings (Containing Spaces)?

I was trying to build a vector of strings.
Some of the strings also contain Spaces.
That's why I was using getline(cin,string_name).
My code looks like
for(int i=0;i<n;++i)
{
getline(cin, s);
vec.push_back(s);
}
When I was taking input
ADAM BOB JOHNSON
It stopped after taking two input words, and the vector contents displayed are
(HERE SPACE IS DISPLAYED)ADAM BOB
What does it mean.Is it taking NULL string as input for the first string ?
It will be really helpful if someone tells me how to take the strings and display it.Thanks.
Abhijit,
Your information is, obviously, not enough. Assuming that your code is written on C++, I made this test cpp:
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> vec;
std::string s;
int n = 1;
for(int i = 0; i < n; ++i)
{
getline(std::cin, s);
vec.push_back(s);
std::cout << vec.at(i) << std::endl;
}
return 0;
}
Compiled with g++ and fed it with "ADAM BOB JOHNSON" string on input. Everything worked as it planned and it output was exact same as input. So I can see no error in here.
Sorry, cannot make it a comment due to insufficient reputation so far.
UPD: Found the issue. getline first gets '\n', we left after '3' (which is needed for std::cin >> n;) hence, you just need to ignore one string. The code:
#include <iostream>
#include <vector>
#include <string>
int main()
{
int n;
std::cin >> n;
std::vector<std::string> vec;
std::string s;
std::getline(std::cin, s);
for(int i = 0; i < n; ++i)
{
std::getline(std::cin, s);
vec.push_back(s);
// std::cout << vec.at(i) << std::endl;
}
for(int i=0;i<n;++i){
std::cout << vec[i] <<" " << std::endl;
}
return 0;
}
works fine for me.
And yep, #pmaxim98 made it first, sorry, was editing the reply and haven't seen your comment.

Trying to open file and copy it word by word with vector

I'm trying to open a file and read it word by word. I can't figure out where my issue is as it seems to break down after opening the file.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <vector>
#include <array>
using namespace std;
int main()
{
string path, test;
ifstream inputFile;
vector<string> words;
cout << "What is the path for the input file? ";
getline(cin, path);
inputFile.open(path, ios::in);
while (!inputFile.eof())
{
cin >> test;
words.push_back(test);
}
for (int i = 0; i < words.size(); i++)
{
cout << words.at(i) << endl;
}
inputFile.close();
return 0;
}
while (!inputFile.eof())
{
cin >> test;
words.push_back(test);
}
There are two problems here:
You opened inputFile but then attempt to read from std::cin
"while (!inputFile.eof())" is always the wrong thing to do.
Well, there's also a third problem here:
Using a debugger would've immediately identified both problems. As an example, I loaded the compiled code in a debugger and stepped through it. The issues were readily apparent.
#Sam has all the things you did wrong.
But an alternative to using a loop is just to use iterators to build the array.
std::ifstream file(path);
std::vector<std::string> words(std::istream_iterator<std::string>(file),
std::istream_iterator<std::string>());
To print it out you can use copy.
std::copy(std::begin(words), std::end(words),
std::ostream_iterator(std::cout, "\n"));
Currently this will break words using white space as the separator between words. This means punctuation etc will be included with words. Look here on how to get the streams to treat punctuation as space: How to tokenzie (words) classifying punctuation as space
Thanks to everyone for the help. Here is the final code (for anyone who ends up Googling this in the future)
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <vector>
#include <array>
using namespace std;
int main()
{
string path, test;
ifstream inputFile;
vector<string> words;
cout << "What is the path for the input file? ";
getline(cin, path);
inputFile.open(path, ios::in);
while (inputFile >> test)
{
words.push_back(test);
}
for (int i = 0; i < words.size(); i++)
{
cout << words.at(i) << endl;
}
inputFile.close();
return 0;
}

C++ test CIN on one line

I've recently started teaching myself C++, and after having written a lot of user input code, it's made me wonder if there's a simpler way of handling it.
For example, the normal way of doing it would be like this:
#include <iostream>
using namespace std;
int inp;
int guess = 13;
void main(){
cout << "Guess a number: ";
cin >> inp;
if (inp == guess)
cout << endl << "Nice.";
}
But what I want to do is:
#include <iostream>
using namespace std;
int guess = 13;
void main(){
cout << "Guess a number: ";
if (cin == guess)
cout << endl << "Even nicer.";
}
Is there a way to do this? Or this that just improper C++ standard?
In short: No, it's not possible to do as you want it.
You need to understand, that >> is actually a function call of
template<typename T>
std::istream& operator>>(std::istream& is, T& result);
and == is a function call to
template<typename T>
bool operator==(const std::istream&,const T& x);
Where the latter is used to check the stream state, and doesn't extract any user input.
To compare the input the result needs to be extracted from the std::istream in 1st place.
Well you can do it in one line but you don't really need to. But here are some examples anyway
//This will work for a char
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
char test = 'a';
if (getch()== test)
cout<<"\n Works";
return 0;
}
And if you really want
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int x =1;
int y;
for( cin >> y ; x == y ; )
{
cout<<"\n Works";
break;
}
return 0;
}
Or as NathanOliver said you could simply do this
if( cin >> inp && inp == guess )
But really you want to keep it simple as this will confuse others as well as yourself after some time. You want to leave your code as easy as possible

C++ Making a char array recognise spaces upon input

I'm trying to make a program that flips the words you input. The problem comes when I try to write the word and it asks twice for the input:
cin >> Arr >> myStr;
It is logical that it ask twice but everytime I try to use getline the compiler gives out an error (and even if it worked I have to give the input twice) and I need it to include spaces in the character array.
Here is my full code:
#include <iostream>
#include <string>
using namespace std;
string myStr;
string newVal;
int i;
int main()
{
char Arr[i];
cout << "Enter: ";
cin >> Arr >> myStr;
for (i = myStr.length(); i >= 0; i--)
{
cout << Arr[i];
}
cout << endl;
return 0;
}
The loop works.
The first problem can be corrected by achieving the proper use of getline.
The second one, I have got no idea (use a single input to assign two variables).
Thanks in advance, and I apologise if this is too much of a ridiculous question.
Maybe you can try to have a look to this solution that it's more C++ style than yours:
#include <iostream>
#include <string>
int main() {
std::string myStr;
std::cout << "Please give me a string: ";
if(std::getline(std::cin, myStr)) {
for(std::string::reverse_iterator it = myStr.rbegin();
it != myStr.rend();
++it) {
std::cout << *it;
}
std::cout << std::endl;
}
}
I suggest to you to use always std::string in C++ because has all the methods and function that you could need. So don't waste your time with char array like you do in C.
Here it is, as I said. I was digging around and came up with this:
#include <iostream>
#include <string>
using namespace std;
string myStr;
int i;
int main()
{
cout << "Enter: ";
getline (cin, myStr);
i = myStr.size();
cout << i << endl;
char Arr[i];
for (int a = 0; a <= i; a++)
{
Arr[a] = myStr[a];
}
for (i; i >= 0; i--)
{
cout << Arr[i];
}
return 0;
}
I did not know string contents could also have array-like behaviour. Test it out! Works like a charm (as far as tested).
The way I formatted the code it takes no more than 27 lines of code.
Thanks everyone involved, you helped me a lot.
P.S: Couldn't answer before, I can't do it soon enough with my reputation.