Extracting and storing data to ostream - c++

Is it possible to store data to an ostream like this
void write(std::ostream& os){
int x,y = 0; bool b = true;
os<<x<<" "<<y<<" "<<b<<std::endl;
}
and then extract data from it like this
void read(std::istream& is){
unsigned int x,y,b;
is>>x>>y>>b; // I want to take x,y,b and make store them in a object but it is not important I want to know if I can extract information from istream like this and use x,y,b
}
I tried to make a simple program to just try that
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char const *argv[]) {
std::fstream file(argv[1]);
if (!file.is_open()){
std::cerr<<"erreur"<<std::endl;
return 1;
}
bool v = false;
size_t x = 1;
size_t y = 2;
for(size_t i=0;i<4;i++) {
file<<v<<" "<<x<<" "<<y<<std::endl;
}
for (size_t j = 0; j < 4; j++) {
bool b; size_t a; size_t c;
file>>b>>a>>c;
std::cout<<b<<a<<c<<std::endl;
}
return 0;
}
but my output is this:
026422044
026422044
026422044
026422044

After closing and reopening the file my problem fixed.
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char const *argv[]) {
std::ofstream file(argv[1]);
if (!file.is_open()){
std::cerr<<"erreur"<<std::endl;
return 1;
}
bool v = false;
size_t x = 1;
size_t y = 2;
for(size_t i=0;i<4;i++) {
file<<v<<" "<<x<<" "<<y<<std::endl;
}
file.close();
std::ifstream file1(argv[1]);
if (!file1.is_open()){
std::cerr<<"erreur"<<std::endl;
return 1;
}
for (size_t j = 0; j < 4; j++) {
size_t b; size_t a; size_t c;
file1>>b>>a>>c;
std::cout<<b<<a<<c<<std::endl;
}
return 0;
}

Related

Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeef3ffff8)

#include <iostream>
#include <string.h>
using namespace std;
int palindrome(char str1[], int n){
int result = 1;
for(int i = 0; i<=(n/2)-1 ;i++){
if(str1[i]!=str1[n-1-i]){
result = 0;
break;
}
}
return result;
}
void copyArrayChar(char *src, char *dest,int startSrc, int size){
for(int i=0; i<=size-1; i++){
src[startSrc + i] = dest[i];
}
}
int patternj(char str1[], int n){
int result = 0;
int check;
check = palindrome(str1, n);
if(n==1||n==0){
result = 1;
} else if(check == 1){
char strL[n/2], strR[n/2];
copyArrayChar(str1, strL, 0, n/2);
copyArrayChar(str1, strR, (n/2)+1, n/2);
result+= patternj(strL,n/2) + patternj(strR, n/2);
}
return result;
}
int main(int argc, const char * argv[]) {
string str[100000];
int strLength[100000], result[100000];
char str1[100000][100000];
int ni;
cin >> ni;
for(int i=0;i<=ni-1;i++){
getline(cin,str[i]);
strLength[i] = (int) str[i].length();
str[i].copy(str1[i],strLength[i],0);
result[i]= patternj(str1[i], strLength[i]);
}
return 0;
}
Hi, so I've written this code to check for patternj strings but for some reason it gives me an error with this name "Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffeef3ffff8)". I don't quite understand why this is happening.

transmission a function pointer to another program file

i want to create a link between two programs throughout the execs functions .
my idea is to create function then point on it by a function pointer then send it to the other program to test it . this is my first programenter code here
1- is this possible ?
2- how ?
i get this idea because i find each time to change the function name in the main function but the remainning still as it was but if i send a pointer function as a character pointer then my programm still as it without changing
#include <iostream>
#include <cstdlib>
#include <unistd.h>
using namespace std;
void
Random(int* ,const int );
int*
selection_sort(int *arr ,const int length)
{
int i = 0,minIndex{0},tmp{0},k{0};
while(i < length-1) // T(n-1) * C1
{
minIndex = i; // Tn * C2
for(int j = i+1 ; j < length ; j++ ) // som(Ti) from i = 0 to i = length-1 )*C3.
{
if((arr)[j] < (arr)[minIndex])
minIndex = j;
}
if(minIndex != i) // Tn * C4
{
tmp = (arr)[i];
(arr)[i] = (arr)[minIndex];
(arr)[minIndex] = tmp;
}
i++;
}
return arr;
}
void
Random(int* array,const int length)
{
srand(time(nullptr));
int i{-1};
while(i++ < length)
{
array[i] = rand()%100;
sleep(0.2);
}
}
int main(int argc,char* argv[])
{
int* (*ptr)(int*,const int ) = selection_sort;
execl("/home/hellios/Documents/Algorithms/sort_Algorithms/main",(char*)ptr,0); // complete the call
return EXIT_SUCCESS;
}
sort_Algorithms/main.c
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <ctime>
using namespace std;
void
Random(int* array,const int length);
int
main(int argc,char* argv[])
{
int* (*ptr)(int *,const int ) =(int* (*) (int*,const int)) argv[1];
int arr1[100],k{0},*arr;
Random(arr1,100);
arr = (*ptr)(arr1,100);
//selection_sort(arr,100);
cout<<"out of selection_sort"<<endl;
for(int j = 0 ; j < 100 ; j++ )
{
printf("[%d]\t", arr[j]);
if(!(++k %10))
cout<<endl;
}
printf("\n");
return EXIT_SUCCESS ;
}
void
Random(int* array,const int length)
{
srand(time(nullptr));
int i {-1};
while(i++ < length)
{
array[i] = rand()%100;
sleep(0.2);
}
}

MSVC Debugger tells me that my vector has more positions than specified

I have declared the following:
const int NUMBER_OF_DIGITS = 16;
std::vector<int> digits(NUMBER_OF_DIGITS);
However when I open the MSVC debugger it shows the following:
This is how I added values to the vector:
for (int i = 0; i < NUMBER_OF_DIGITS; ++i) {
scanf("%d", &digits[i]);
}
Is this normal? Can I just ignore this? Or is this a problem?
Full code(the program is still not ready yet):
#include <iostream>
#include <vector>
#include "stdio.h"
const int NUMBER_OF_DIGITS = 16;
int checksum, tmp1, tmp2, tmp3, sum = 0;
std::vector<int> digits(NUMBER_OF_DIGITS);
std::vector<int> new_digits(NUMBER_OF_DIGITS);
int luhn_checksum(std::vector<int> cardnumber[NUMBER_OF_DIGITS]) {
//step 1: duouble every second number
for (int i = 1; i < NUMBER_OF_DIGITS; i += 2) {
new_digits[i] = digits[i] * 2;
if (new_digits[i] > 9) {
//if the product is larger than 9 we will add the two numbers together
//example: 9 * 2 = 18 so we will add 1 + 8 to get 9
tmp1 += new_digits[i] % 10;
new_digits[i] /= 10;
tmp1 = 0;
}
}
//step 2: sum all the values
for (int i = 0; i < NUMBER_OF_DIGITS; ++i) {
checksum += new_digits[i];
}
return checksum;
}
void get_card_numbers(void) {
for (int i = 0; i < NUMBER_OF_DIGITS; ++i) {
scanf("%d", &digits[i]);
}
}
void initialize(void) {
for (int i = 0; i < NUMBER_OF_DIGITS; ++i) {
digits.push_back(0);
new_digits.push_back(0);
}
}
int main() {
initialize();
get_card_numbers();
printf("checksum is: %d\n", luhn_checksum(&digits));
std::cout << digits.size() << std::endl;
int x; scanf("%d", &x);
return 0;
}
The constructor you're using for digits is setting the size by specifying the count. So after calling push_back you've just added another 16 to the vector. Use a different constructor that doesn't set the count.
int _tmain(int argc, _TCHAR* argv[])
{
const int NUMBER_OF_DIGITS = 16;
std::vector<int> digits(NUMBER_OF_DIGITS);
//std::vector<int> digits;
int digitsLen = digits.size();
// Here is 16
for (int i = 0; i < NUMBER_OF_DIGITS; ++i) {
digits.push_back(0);
}
int digitsLen2 = digits.size();
// Here is 32
return 0;
}
Cleaned up your code a bit:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
static const size_t NUMBER_OF_DIGITS = 16;
class cards {
public:
cards();
void read();
int luhnChecksum() const;
private:
vector<int> digits;
};
cards::cards() : digits(NUMBER_OF_DIGITS, 0)
{
}
void cards::read() {
for_each(digits.begin(), digits.end(), [](int& i) { cin >> i; });
}
int cards::luhnChecksum() const {
vector<int> newdigits(digits.begin(), digits.end());
for (size_t i=1; i<NUMBER_OF_DIGITS; i += 2) {
newdigits[i] = digits[i] * 2;
if (newdigits[i] > 9) {
int tmp1 = newdigits[i] % 10;
newdigits[i] /= 10;
newdigits[i] += tmp1;
}
}
return accumulate(newdigits.begin(), newdigits.end(), 0);
}
int main() {
cards c;
c.read();
cout << "checksum = " << c.luhnChecksum() << endl;
return 0;
}

Verifying changes in array after memset to default value

I have the following code in which I: (1) initialize an array with default values; (2) do something with the array; (3) check the array is still default. I'm unsure about (3).
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include <string.h>
#define ARRAY_MAX 10
#define DEFAULT_VALUE 0
int main(int argc, char *argv[])
{
uint32_t array[ARRAYMAX];
memset(array, DEFAULT_VALUE, sizeof(array));
do_something_with(array);
check_array_is_default(array);
return 0;
}
The way I would check if the array is only default values is the following (i.e. this is how I would write the check_array_is_default() function):
int check_array_is_default(uint32_t *array)
{
int i;
uint32_t defval = DEFAULT_VALUE;
for (i = 0; i < ARRAY_MAX; i++)
{
if (memcmp((array + i * sizeof(uint32_t)), &defval, sizeof(uint32_t)))
{
return 0;
}
}
return 1;
}
memset fills bytes, not words so you need to look at the bytes individually:
int check_array_is_default(uint32_t *array)
{
char *p = (char *)array;
int n = ARRAY_MAX * sizeof(array[0]);
for (int i = 0; i < n; i++) {
if(p[i] != DEFAULT_VALUE) {
return 0;
}
}
return 1;
}

C linking programs and using methods from other programs on main function (sudoku

NOTE: skip to bottom for real question
Hey guys, right now I am in a rut where I know the basics how to solve my sudoku program, but if I did it the way i know how it would be ugly, long and a lot of unnecessary code.
Right I have sudoku.cc, sudokuboard.cc, sudokuboard.h, stack.cc, and stack.h,
So as of right now it doesn't matter what my stack.cc and my stack.h are because they are rather generic and anyone can find the programs to them and frankly I don't underdstand why I even need to include the stack.cc/h due.
My sudoku.cc as of right now is:
#include <iostream>
#include <cassert>
#include <fstream>
#include "sudokuboard.h"
#include "stack.h"
using namespace std;
int main (void)
{
FILE *fp = fopen("test.txt","r");
char sudoku_grid[9][9];
char ch;
if(fp != NULL)
{
for(int i = 0; i < 9; i++)
{
for(int j = 0; j < 9; j++)
{
ch = fgetc(fp);
sudoku_grid[i][j] = ch;
}
ch = fgetc(fp);
}
for(int i = 0; i< 9;i++)
{
for(int j= 0; j<9;j++)
cout<<sudoku_grid[i][j];
cout<<endl;
}
}
return 0;
}
Which so far does nothing but print out the file I gave it and have it stored in a 2D array.
My sudokuboard.h is
#include <iostream>
#define SDIM 9
class SudokuBoard {
public:
//------------------------------------------------------------------------
SudokuBoard();
// Construct a blank sudoku board
//------------------------------------------------------------------------
//------------------------------------------------------------------------
void print(std::ostream & ostr) const;
// display it. duh.
//------------------------------------------------------------------------
//------------------------------------------------------------------------
void place(size_t r, size_t c, char digit);
// PRE: safe(r,c,digit)
//------------------------------------------------------------------------
//------------------------------------------------------------------------
void remove(size_t r, size_t c, char digit);
// PRE: get(r,c) == digit
//------------------------------------------------------------------------
//------------------------------------------------------------------------
char get(size_t r, size_t c) const;
// Return the digit at (r,c) on the board. or ' ' if blank.
//------------------------------------------------------------------------
//------------------------------------------------------------------------
bool safe(size_t r, size_t c, char digit) const;
//
//------------------------------------------------------------------------
//------------------------------------------------------------------------
bool done() const;
// Return true iff every cell has a number
//------------------------------------------------------------------------
private:
std::string rows[SDIM];
};
and my sudokuboard.cc:
#include <iostream>
#include <cassert>
#include "sudokuboard.h"
#define ASSERTBOUNDS assert(0 <= r and r < SDIM and 0 <= c and c < SDIM)
SudokuBoard::SudokuBoard()
{
for (size_t i = 0;i<SDIM;i++) {
rows[i] = "";
for (size_t j=0;j<SDIM;j++)
rows[i] += ' ';
}
}
void SudokuBoard::place(size_t r, size_t c, char digit)
{
ASSERTBOUNDS;
assert(safe(r,c,digit));
}
void SudokuBoard::remove(size_t r, size_t c, char digit)
{
ASSERTBOUNDS;
assert(get(r,c)==digit);
rows[r][c] = ' ';
}
char SudokuBoard::get(size_t r, size_t c) const
{
ASSERTBOUNDS;
return rows[r][c];
}
void SudokuBoard::print(std::ostream & ostr) const
{
for (size_t i=0;i<SDIM;i++)
ostr << rows[i] << std::endl;
}
bool SudokuBoard::safe(size_t r, size_t c, char digit) const
{
for(size_t r=0; r<SDIM; r++)
for(size_t c=0; c<SDIM; c++)
if (get(r,c) == digit)
return false;
for(size_t c=0; c<SDIM; c++)
for(size_t r=0; r<SDIM; r++)
if (get(r,c) == digit)
return false;
return true;
}
bool SudokuBoard::done() const
{
for (size_t r=0;r<SDIM;r++)
for (size_t c=0;c<SDIM;c++)
if (rows[r][c]==' ')
return false;
return true;
}
So as of right now I want to use sudokuboard.cc methods and use the SudokuBoard() in my sudoku.cc because I know if I do that I will be able to use the useful methods provided by Sudokuboard.cc thus making my code seem a lot cleaner because it isn't all cluttered up on one program.
So as of right now I think the gateway to linking these two programs together in order to maximize my space I would have to set my current 2D array which is sudoku_grid to be part of Sudokuboard() some how.
The problem is that I literally have no blinkin idea how to hook this puppies up. I know I cannot do sudoku_grid = Sudokuboard() because even if it did work, it would probably set all the arrays to being just spaces.
Anyone have a solution of where to start off?
At the top of the main file put #include "sudokuboard.h" so that the compiler knows it's there. Next, at the top of your int main() you need to create an instance of the SudokuBoard class, with SudokuBoard mainBoard;, then you can access it's methods via mainBoard.doSomething(); somewhere else in the main. I'd recommend creating a new method in the SudokuBoard class that reads data from a file and places it directly into SB's private std::string rows[SDIM]; array from within (basically move most of the code from main into the class). With the code as-is, this should work assuming I didn't mangle any of the names:
#include "sudokuboard.h"
int main (void) {
SudokuBoard mainBoard;
FILE *fp = fopen("test.txt","r");
char sudoku_grid[9][9];
char ch;
if(fp != NULL) {
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++ ) {
ch = fgetc(fp);
//sudoku_grid[i][j] = ch;
//set mainBoard's internal state, etc here
mainBoard.place(i,j,ch);
}
ch = fgetc(fp);
}
for(int i = 0; i< 9;i++) {
for(int j= 0; j<9;j++) cout<<sudoku_grid[i][j];
cout<<endl;
}
}
return 0;
}