Represent a file with 0x00 as a string [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I want to represent my file as a string but I have a problem the file contains a 0x00 and my string gets terminated right there.How to solve this?

If you can't use the null as the termination character you have very few options:
a) write the string size prior to the string:
005Hello
011Hello\0World
b) use fixed length strings
c) prepend non-terminating nulls with a special char like '\'. If '\' appears in your string, write it twice "\". Reverse the logic when reading them back.

I have a txt file like this in binary 0x61 0x61 0x61 0x00 0x62 0x62 0x62
"txt file" in binary ? - I don't know what does it mean .
But if you have values separated by spaces you can try using std::vector of std::string
(which doesn't use null termination)
std::ifstream fin("input.txt");
std::vector<std::string> v;
std::copy(std::istream_iterator<std::string> (fin),
std::istream_iterator<std::string> (),
std::back_inserter(v) );
std::vector<std::string>::iterator it =v.begin();
for(;it!=v.end();++it)
std::cout<< *it<<" ";

Be sure to read your file in binary mode:
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
std::string read_file_as_string(const char* filename) {
std::ifstream input(filename, std::ios::binary);
if (!input) {
std::perror("Great failure");
std::exit(1);
}
std::stringstream contents;
contents << input.rdbuf();
return contents.str();
}
int main() {
std::string s = read_file_as_string("Derp.exe");
std::cout << "s.size() = " << s.size() << '\n';
for(unsigned char c : s) {
std::cout << std::hex << static_cast<unsigned int>(c) << ' ';
}
std::cout << '\n';
}

Related

Enter a string and divide it in words [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I need to code a program based which can compare words of a sentence or paragraph to a database, as if it were a text corrector. My problem here is that I have to enter on the console the text I want to correct as a string and then divide it in words stored in a vector of strings in C++. I tried a thousand ways but I cannot get it done.
Here is the code I last tried:
std::cout << "Enter the text: ";
std::string sentence;
std::vector<std::string> vText;
while (getline(std::cin, sentence)){
std::stringstream w(sentence);
std::string word;
while(w >> word)
vText.push_back(word);
}
When I execute this code, I got nothing, as if the program did nothing. Can you help me please?
This is the final thing (a piece):
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main(){
std::cout << "Introduzca una frase: ";
std::string frase;
std::vector<std::string> vTextoAnalizar;
while (getline(std::cin, frase)){
std::stringstream w(frase);
std::string palabra;
while(w >> palabra)
vTextoAnalizar.push_back(palabra);
}
for (int i=0;i<vTextoAnalizar.size();i++){
std::cout << vTextoAnalizar[i] << std::endl;
}
return 0;
}
Firstly, welcome to stack exchange. Your question has been down voted as you have not made a reasonable effort to ask a good question.
Please take particular note of How to create a Minimal, Complete, and Verifiable example.
I think what you are trying to do is something like this:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
std::vector<std::string> read_text() {
std::cout << "Enter the text: ";
std::string sentence;
std::string word;
std::vector<std::string> vText;
while(getline(std::cin, sentence)){
std::stringstream ss(sentence);
while ( getline( ss, word, ' ' ) ) {
if (word.compare("quit") == 0)
return vText;
vText.push_back(word);
}
}
}
int main() {
std::vector<std::string> test_vector = read_text();
std::cout << "Vector : " << std::endl;
for (int i=0;i<test_vector.size();i++){
std::cout << test_vector[i] << std::endl;
}
}
This will split on spaces, and add your words to the vector at the end of each sentence. I imagine that there are more intelligent ways of parsing, but this should get your test code working.
Hope that helps.

Understanding stringstream [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have never used stringstream before and was given a sample code but with no explanation of what was happening in the code. If someone could explain each line's purpose that would be great. I have looked in multiple places but cant seem to pin down the second line.
#include <sstream> // i know this line includes the file
stringstream ss(aStringVariable);// this line in particular
ss >> aVariable;
getline(ss, stringVariable2HoldValue, ‘|’);
There's a constructor for std::stringstream that takes a std::string as a parameter and initializes the stream with that value.
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::stringstream ss("foo bar");
std::string str1, str2;
ss >> str1 >> str2;
std::cout << "str1: " << str1 << std::endl;
std::cout << "str2: " << str2 << std::endl;
}
This code initializes a stringstream, ss, with the value "foo bar" and then reads it into two strings, str1 and str2, in the same way in which you would read from a file or std::cin.

C++ read from file and know if stream is string or numeric [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 8 years ago.
Improve this question
I've a file like this
A 2 3 4 6
B 10 1 2 6
and when I read it I need to check if I read a character or a number. But I've no idea how...
string fileName = "/Users/Fry/Desktop/file/file/file.txt";
ifstream myReadFile;
myReadFile.open(fileName);
char output[1000];
if (myReadFile.is_open())
{
while (!myReadFile.eof())
{
myReadFile >> output;
cout << output << endl;
}
}
You can use standard C function std::isdigit declared in header <cctype> that to check whether the first character (or each character) of the read string is a digit and if so then apply C++ function std::stoi
For example
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
//...
std::string fileName = "/Users/Fry/Desktop/file/file/file.txt";
std::ifstream myReadFile( fileName );
std::string data;
while ( myReadFile >> data )
{
if ( std::isdigit( data[0] ) )
{
std::cout << "It is number " << std::stoi( data ) << std::endl;
}
else
{
std::cout << "It is string " << data << std::endl;
}
}
You can parse the file string by string, and check whether each small string is a number or not. Something like:
#include <fstream>
#include <cctype>
#include <sstream>
...
std::string tmp;
while (myReadFile >> tmp){
// you got a string...
if (is_number(tmp)){
// it's a number
}
else{
// it's not a number
}
}
To check whether a string is a number or not, you can use the following function, which is be able to handle multiple-char number like 10 or non-numbers like 123abc45.
bool is_number(const std::string& s){
return !s.empty() && s.find_first_not_of("0123456789") == std::string::npos;
}
Include <cctype> and use isdigit() and isalpha() to check the characters read.
I'm not sure if it's relevant in this case; it looks to me like
you have a very fixed format, and can know exactly whether you
should expect a letter or a number. But otherwise, you can
always peek ahead:
myFile >> std::skipws; // Since we're going to use unformatted input
if ( std::isalpha( myFile.peek() ) ) {
// It's a letter, extract it into a char or a string
} else {
// It's (hopefully) a number, extract it into an int
}
std::istream::peek does not extract the character, so it is
still there for the normal formatted extractors. And it returns
an int (not a char) in the correct range for the functions
in <cctype>, so you don't have to worry about the undefined
behavior that results when calling them with a char.
Also, you shouldn't be using the results of >> before checking
to see that it succeeded, and you shouldn't use eof() as
a condition for a loop.

How to read a space character from a text file in c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
In c++, ascii characters has a default value. Like ! has a value of 33, "," has also a value of 44 and so on.
inside my text file "hehe.txt" is. ;!,.
#include <iostream>
#include <fstream>
int main() {
std::ifstream file("hehe.txt");
if(file.eof())
return 0;
char ascii;
while(file>>ascii) {
std::cout << (int)ascii << " ";
}
system("pause");
}
Output is 59 33 44 46.
Edit: How may I prevent space to be ignored as being read from the text file when I run my program? Suppose I added space after the last character ;!,.thus, the output must be 59 33 44 46 32. Hope someone could give me an idea how to do it.
The problem is the separator. When you use file >> ascii this will "eat" all your spaces as these are used as separators.
You can use getline and then iterate over all chars in the string.
std::ifstream file("../../temp.txt");
if(!file)return 0;
std::string line;
while (std::getline(file, line, '\0')){
for(char ascii : line){
std::cout<<(int)ascii << " ";
}
}
system("pause");
return 0;
What is also possible, as dornhege says, is:
while(file >> std::noskipws >> ascii){
std::cout << (int) ascii << "\n";
}
The istream object will skip whitespace as the " " (32) by default. Try adding >> std::noskipws to your stream before reading.

how can i read binary data in c++? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to read and write binary data in C++.I use from ofstream and ifstream classes but it can't read some chars like 9,13,32.If is there another way to read and write theme.
Open the file using the std::ios::binary flag and then use .read(buffer,length); and .write(buffer,length); rather than the streaming operators.
There are some examples here:
https://cplusplus.com/reference/istream/istream/read/
https://cplusplus.com/reference/ostream/ostream/write/
Here is a program that does this:
#include <iostream>
#include <fstream>
int main(int argc, const char *argv[])
{
if (argc < 2) {
::std::cerr << "Usage: " << argv[0] << "<filename>\n";
return 1;
}
::std::ifstream in(argv[1], ::std::ios::binary);
while (in) {
char c;
in.get(c);
if (in) {
::std::cout << "Read a " << int(c) << "\n";
}
}
return 0;
}
Here is an example of it being run in Linux:
$ echo -ne '\x9\xd\x20\x9\xd\x20\n' >binfile
$ ./readbin binfile
Read a 9
Read a 13
Read a 32
Read a 9
Read a 13
Read a 32
Read a 10
This is a basic example (without any error check!):
// Required STL
#include <fstream>
using namespace std;
// Just a class example
class Data
{
int a;
double b;
};
// Create some variables as examples
Data x;
Data *y = new Data[10];
// Open the file in input/output
fstream myFile( "data.bin", ios::in | ios::out | ios::binary );
// Write at the beginning of the binary file
myFile.seekp(0);
myFile.write( (char*)&x, sizeof (Data) );
...
// Assume that we want read 10 Data since the beginning
// of the binary file:
myFile.seekg( 0 );
myFile.read( (char*)y, sizeof (Data) * 10 );
// Remember to close the file
myFile.close( );