Is there any problem with this code? [closed]
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main()
{
cout << "Hello.";
ifstream attack,output;
attack.open("CattackList");
output.open("finaltestOutput.txt");
if (!attack)
cout << "file1 not opened.\n";
if (!output)
cout << "file2 not opened.\n";
char buf1[100],buf2[100];
attack.getline(buf1,100);
int count = 0, C=0;
cout << "hello";
while (!attack.eof())
{
C++;
cout << "ok";
output.open("finaltestOutput");
while (!output.eof())
{
output.getline(buf2, 80);
if (strncmp(buf1, buf2, 51) == 0)
{
cout << buf2 << endl;
count++;
}
}
attack.getline(buf1, 80);
}
cout << "\nTotal Attacks : " << C << endl;
cout << "Attacks detected: " << count << endl;
return 0;
}
I am not able to get even the first "Hello" to get printed...
Let's see...
#include<iostream>
#include<fstream>
#include<cstring>
Please put a space after each #include
.
if (!attack)
cout << "file1 not opened.\n";
if (!output)
cout << "file2 not opened.\n";
Error messages should go to cerr
, not cout
.
char buf1[100],buf2[100];
attack.getline(buf1,100);
Did you allow space for the null at the end of the string? Also, one space after each comma.
int count = 0, C=0;
Spaces around binary operators such as =
. Also, single letter variable names are discouraged.
output.open("finaltestOutput");
You already opened this file. Why are you opening it again? Also, points off for naming an input file stream output
.
output.getline(buf2, 80);
if (strncmp(buf1, buf2, 51) == 0)
Where are you getting the numbers 80
and 51
?
There may be more; start with that.
Is there any problem with this code?
- It's C++ not C.
- The indentation is broken.
- Stick to one statement per line.
- It is full of inexplicable magic constants.
Sort those problems out first and then ask again.
In, your code you dint given the Filename Extensions at two parts one is at attack.open("CattackList");
and the other is at output.open("finaltestOutput");
. May be this causing the files not to be Opened and getting the unexpected results.
精彩评论