| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
string problems
i have got this code
Code:
ofstream a_file ( "example.txt" );
a_file<<"hello";
a_file.close();
char *buffer;
long size;
ifstream file ("example.txt", ios::in|ios::binary|ios::ate);
size = file.tellg();
file.seekg (0, ios::beg);
buffer = new char [size];
file.read (buffer, size);
file.close();
if (buffer == "hello"){
cout << "ok\n";
}
cout << buffer;
the output is 'hello'. How come the comparison of (buffer == "hello") does not equal true? |
|
#2
|
|||
|
|||
|
Hi MMayfield45. I've worked with C (not so much with C++) but...aren't you supposed to use
strcmp() to see if the strings match? strcmp(buffer,"hello") I don't know if strings can be compared with "==" in C++ (at least in C you cann't). Good Luck Anibal. PS: I apologise if I'm mistaken....simply trying to help, as I was helped before!! |
|
#3
|
|||
|
|||
|
thanks, i got the reply of another forum.
Code:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
ofstream a_file ( "example.txt" );
//learn to check return values!
a_file<<"hello";
a_file.close();
string buffer, tmp;
ifstream file ("example.txt", ios::in);
//learn to check return values!
while (!file.eof()){
getline(file, tmp);
buffer += tmp;
}
file.close();
if (buffer == "hello") {
cout << "ok\n";
}
cout << buffer << endl;
return 0;
}
|
|
#4
|
||||
|
||||
|
So the problem was all with this line?
ifstream file ("example.txt", ios::in|ios::binary|ios::ate); I agree with Anibal; I think it's better practice to use strcmp. |
|
#5
|
|||
|
|||
|
Quote:
Please explain , why the blue -line is trouble maker. |
|
#6
|
||||
|
||||
|
Oh, don't ask me... I was simply comparing the two scripts...
That was the only difference I had noticed... Perhaps MMayfield45 can explain how the problem was solved. |
|
#7
|
|||
|
|||
|
The reason thr first script didn't work is because
The reason thr first script didn't work is because you cannot open a text file with the ios::binary option.
-Zak |
|
#8
|
||||
|
||||
|
Thanks for clearing that up Zak
|
|
#9
|
|||
|
|||
|
Quote:
Why not? You may not get the results you want, but you should alway be able to open a file as binary. After all, it's stored as bits and bytes. And if you know what you are doing it will always work. |
|
#10
|
|||
|
|||
|
Quote:
Yep. You gotta use strcmp(). |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > string problems |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|