How to copy array to file in c++ [closed] - c++

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 read array from the text file and I want to copy this array's elements to another text file
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int ARRAY_SIZE = 5;
int numbers[ ARRAY_SIZE];
int count = 0;
cout << "1. before opening file\n";
ifstream inputFile;
inputFile.open("test.txt");
if (!inputFile)
{
cout << "error opening input file\n";
return 1;
}
cout << "2. after opening file\n";
cout << "3. before reading file, count = " << count << '\n';
while (count < ARRAY_SIZE && inputFile >> numbers [ count])
count++;
inputFile.close();
cout << "4. after reading file, count = " << count << '\n';
cout<< "The numbers are : ";
for (int i = 0; i < count; i++)
cout << numbers[i] << " ";
cout<< endl;
cout << "5. Program ending" << endl;
return 0;
}
I added this code but it doesn't work. How can I copy this array's elements to destination.txt file?
ofstream fstreamFile("destination.txt");
copy(
numbers,
numbers + sizeof(numbers),
ostream_iterator<int>(fstreamFile)
);
my elements are 10,20,30,40 but in the destination.txt file, output is "10203040160641613632767-1973944304-...."

The problem is that you use sizeof for the end "iterator" of the array.
The sizeof operator returns the size in bytes, not in array elements. That means you will go way out of bounds beyond the end of the array.
I suggest you change to use the standard std::begin and std::end helper functions to get the "iterators" for the array:
std::copy(std::begin(numbers), std::end(numbers), ...);
For proper arrays (but not for pointers, and remember that arrays decays to pointers very easily) those functions will do the right thing.

Related

How to know how many digits are in a numeral in C++ [duplicate]

This question already has answers here:
C++ - how to find the length of an integer
(18 answers)
How to count amount of digits in a given number in c++
(3 answers)
Closed 1 year ago.
I have a C++ code that asks for a number to work with. I want to use the loop for with the length of this number, such as what we are used to do in JavaScript using .length property.
For example:
the input is: 2563
int input;
for (i = 0; i < input.length; i++)
It is supposed to repeat 4 times.
How could I do it?
If you always receive the number via some text input (command line or a text file) then there's no reason to do modulo arithmetic. If your loop is even tightly coupled to the number of symbols received, it makes even less sense to operate on the integer. Instead, receive the input as a string.
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "Enter a positive integer: ";
std::getline(std::cin, input);
for (int i = 0; i < input.length(); i++) {
std::cout << "Digit number " << i << " is " << input[i] << std::endl;
}
}
NOTE input[i] is a character, and any arithmetic operations on that character will not work the same way you expect it to on the integer's individual digits. If you want the number to work with numerically (instead of just symbolically) you can convert to an integer using the std::stoi family of functions ("string to integer").
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "Enter a positive integer: ";
std::getline(std::cin, input);
for (int i = 0; i < input.length(); i++) {
std::cout << "Digit number " << i << " is " << input[i] << std::endl;
}
int value = std::stoi(input);
std::cout << "The number times 2 is " << value * 2 << std::endl;
}
NOTE The std::stoi family of functions provide error checking functionality. My above example omits that for simplicity, and because this sounds like a school assignment where input validation is the user's problem.

Corrupted array [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 5 years ago.
Improve this question
char arr[10]="\0",arr1[2][5]={'\0'};
cout<<"enter the full line : ";
gets(arr);
for (int i=0;i<1;i++)
{
for (int j=0;j<10;j++)
{
if(j<=4)
{
arr1[0][j]=arr[j] ;
}
else if (j>4)
{
arr1[1][j-5]=arr[j] ;
}
}
}
for(int j=0;j<5;j++)
{
cout<<arr1[0][j]<<" ";
}
cout<<endl;
for(int j=0;j<5;j++)
{
cout<<arr1[1][j]<<" ";
}
Here what i am trying to do is converting a 1d array in to 2d array.
my main purpose is to store 1d array on a 2d and when the first row is completed it should shift the string to next row it is doing all the as i have declared the arr[10] and inputting 10 charcter string through get(arr) it is storing the array as i want but at the end displays an error window i dont know why the program is running perfect as well as giving this error window
my input : hanzlaamja (10charcters)
my output:
h a n z l
a a m j a
according to my wish but the main problem is the error window.
note : there is nothing in error box or warning box.
My program is working perfectly, but i am getting an error of array corruption.
Can anybody help me out? I would be very thankful
please see this error message
full picture
The problem is that you read in 10 characters (e.g. "hanzlaamja") and the string termination character '\0', which is automatically added by gets. Thereby you exceed array bounds, as this would require space for 11 characters. So it would already work if you wrote char arr[11];. But as mentioned in the comments, do not use gets; it is unsafe and it does not prevent you from exceeding array bounds. The following snippet shows how to do this part better:
...
char arr[11]="\0",arr1[2][5]={'\0'};
cout<<"enter the full line : ";
// gets(arr);
if (!fgets(arr,11,stdin)) {
cout << "no value read." << endl;
return 1;
}
...
A lot of your loops could be written shorter / better readable. But that's not the actual topic.
Adding to the great point pointed out by #Stephan Lechner, I have composed a solution "as close as possible" to your original.
Compiled under visual studio 2017.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
cout << "main - start" << endl;
const size_t numOfRows = 2;
const size_t numOfCol = 5;
const size_t numCharsInSingleDimArray = 10;
char arr[numCharsInSingleDimArray] = { '\0' }, arr1[numOfRows][numOfCol] = { '\0' };
cout << "enter the full line : ";
gets_s(arr); // Note:If the buffer (arr) is too small to contain the input line and null terminator, these functions invoke an invalid parameter handle.
cout << "main - entered:" << arr << endl;
char* twoDimArrStartLoc = &(arr1[0][0]); // as user4581301 pointed out, it is also possible to "approach" it by treating the two dimensional array as a contiguous bytes in memory
for (size_t i = 0, j = 0; i< numCharsInSingleDimArray; ++i, ++j)
{
twoDimArrStartLoc[j] = arr[i];
}
cout << "main - after converting the 1d array into 2d array, arr1 is:" << endl;
for (size_t i = 0; i < numOfRows; ++i)
{
for (size_t j = 0; j < numOfCol; ++j)
{
cout << "arr1[" << i << "]" << "[" << j << "]:" << arr1[i][j] << " ";
}
cout << endl;
}
// for debug - you can remove this if not needed...
cout << "main - end, enter any key and press enter to terminate..." << endl;
char tmp;
cin >> tmp;
return 0;
}
Hope it helps.
Cheers,
Guy.
thank you everyone for your support the MAIN mistake i was doing is the use of gets(arr) and doing arr[10] as if you are using function gets(arr) you have to give one extra index which is used by this function gets(arr) i.e. arr[11]
solved :)

Vector duplicates the value [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 6 years ago.
Improve this question
Firstly be mercyful, i'm a beginner in C++.
I wrote this code for my interpreter: Reading a line from source and splitting line to words. I using a vector object for storing words. Here is the code, Source is file descriptor (ifstream):
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
typedef unsigned int UIntegerP;
#define V(X, Y, Z) X##Y##Z
#define Version V(0, 0, 1)
#define Free 0x0
int main(int ACount, char *Arguments[]){
if(ACount < 2){
cout << "Venus Interpreter - Engine V: " << Version << " - Interprate: -I <Source> \n";
}else{
if(Arguments[1][0] == '-' && Arguments[1][1] == 'I'){
if(ACount < 3){
cout << "Error: No input files \n";
}else if(ACount > 3){
cout << "Error: Too much arguments \n";
}else{
ifstream Source(Arguments[2]);
if(Source.good()){
# define __TEST__ 1
string Line;
vector<string> Words;
string Word;
while(getline(Source, Line)){
for(unsigned long Index = 0; Index <= Line.length(); Index++){
if(Line[Index] == ' ' or Line[Index] == '\0'){
Words.push_back(Word); //Inject the Word to Words
Word.clear();
} else {
Word += Line[Index];
}
}
# if __TEST__
cout << Words[0] << "\n";
# endif
//Interpration starts here
Words.clear();
}
}else{
cout << "Error: File does not exist \n";
}
Source.close();
}
}else{
cout << "Error: Unknown operand \n";
}
}
return 0;
}
And this is the file interpreted by program:
10 * 20 / 5 * 10
Asparagas
And this is the output:
10
10
Like you can see here, value is duplicated. What is the problem?
You problem is that for the line 10 * 20 / 5 * 10 you insert the words into your vector, and then print out its first element
#if __TEST__
cout << Words[0] << "\n";
#endif
You then (I assume) think that you are clearing the vector with the following line
Words.empty();
However, this doesn't clear the vector, it returns a boolean showing whether the vector is empty or not (documentation on vector.empty())
To clear your vector you should use vector.clear()
The second time around your loop, when you're processing asparagus, you print the first element in the vector, which is 10, because it's still in the vector from the first getline

C++ How to pass 2 arrays (of strings) to a function, and compare to a string [duplicate]

This question already has answers here:
Size of array object passed to function
(4 answers)
Closed 7 years ago.
I'm a C++ beginner, so talk to me like I'm 5.
Here's what I'm trying to do:
Take user's input into a string userInput
Pass userInput, along with 2 arrays (answers and outcomes), into a function answerCheck
Compare userInput with answers array
If there's a match, output string from outcomes
If no match, loop, ask for userInput
I output the size of answers with answersSize. It outputs 1 instead of the expected 2.
I can't figure out how to pass the information in the arrays to the answerCheck function.
Any suggestions?
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int question1();
bool answerCheck(string[], string[], string);
int main() {
question1();
system("pause");
return 0;
}
int question1() {
cout << "Do you want to go LEFT or RIGHT?" << endl;
string answers[2] = { "left", "right" };
string outcomes[2] = { "you went left", "you went right" };
string userInput = "";
getline(cin, userInput);
// outputs correct size of answers array for testing ======
int answersSize = sizeof(answers) / sizeof(string);
cout << "Correct size of answers: "<< answersSize << endl;
// ========================================================
answerCheck(answers, outcomes, userInput);
return 0;
}
bool answerCheck(string answers[], string outcomes[], string userInput){
int answersSize = sizeof(answers) / sizeof(string);
cout << "Size of answers: "<< answersSize << endl;
for(int i=0; i < answersSize; i++){
if(userInput.find(answers[i]) != string::npos){
cout <<"\n" << outcomes[i] <<"\n" << endl;
return true;
}
}
cout << "Try putting in something else." << endl;
return false;
}
The problem is here:
int answersSize = sizeof(answers) / sizeof(string);
If you print it out, you will find that sizeof(answers) is the size of a pointer (4 or 8 bytes), not the size of the entire array. You need to pass the array size in as a function argument, or else use a class type like std::vector which encapsulates this in a more C++ way.
A general advice for beginners would be to use the C++ such as classes std::vector instead of plain C arrays. So in your example, instead of
string answers[2] = { "left", "right" };
use
std::vector<std::string> answers{ "left", "right" };
and declare your function
bool answerCheck(std::vector<string> const& answers,
std::vector<string> const&outcomes,
string const& userInput)
If you are reading a introductory book and it starts by introducing C-style code first, I would throw it away. A good introduction to C++ is e.g. https://isocpp.org/tour.

Trying to pass an array to a function and find the sum

I am newbie to programming and I am trying to pass an array into a function and add all the elements together and return the sum. The problem is that I am getting a garbage value for the sum. I have researched on how to pass arrays to functions and I do not know if I'm supposed to use a pointer to pass arrays. I am not good with pointers anyways.
Here is my code
#include <cmath>
#include <cstdlib>
using namespace std;
float mean(int);
int sum(int ARRZO[5]);
int total;
int main()
{
int ARRZ[5];
char *inname = "example.txt";
ifstream infile(inname);
if (!infile) {
cout << "There was a problem opening file " << inname << " for reading." << endl;
return 0;
}
cout << "Opened " << inname << " for reading." << endl;
for(int i=0; i<11; i++)
{
while (infile >> ARRZ[i])
{
cout << "Value from file is " << ARRZ[i] << endl;
}
}
total=sum(ARRZ);
cout<<"the sum of the elements in the array is"<<total<<endl;
system("PAUSE");
return 0;
}
int sum(int ARRZO[])
{
int sumz=0;
for (int i=0; i<5; i++)
{
sumz+=ARRZO[i];
cout<<ARRZO[i];
}
cout<<sumz<<endl;
return sumz;
}
You are actually reading all the values from the file in ARRZ[0] because of the inner loop. By the time you get to i=1, you are at the end of the file, and not reading anything.
Remove one loop, and increment i when you have read successfully a value.
I'm not sure what you think this pair of nested loops is supposed to do:
for(int i=0; i<11; i++)
{
while (infile >> ARRZ[i])
{
cout << "Value from file is " << ARRZ[i] << endl;
}
}
But (as #aliexisdm pointed out) the inner loop reads the entire content of the file. What he didn't (at least directly) point out is that you're reading every one of those values into the first element of your array. Then you're getting back to the outer loop, incrementing i, and trying to read the file again -- but since the stream's failbit has been set, all your subsequent attempts at reading are guaranteed to fail.
After that, you add up the 5 items in the array, but since you haven't read anything into 4 of them (and never initialized its contents) you end up with the last item you read from the file + 4 garbage values, giving still further garbage as the result (well, usually anyway -- you really have undefined behavior, so the program could crash and burn instead, but with most current computers, you'll just get some meaningless number).
I, however, would advise changing the program a bit more than just removing one loop and incrementing in the loop that's left. Instead, I'd remove all the (explicit) loops, and make some attempt at making real use of what the standard library provides.
You can read the numbers from the file in one fell swoop:
std::ifstream infile(inname);
std::vector<int> ARRZ ((std::istream_iterator<int>(infile)),
std::istream_iterator<int>());
Then you can sum them all with std::accumulate:
int sum = std::accumulate(ARRZ.begin(), ARRZ.end(), 0);
Finally, you can print out the result:
cout << "The sum of the elements in the array is: " << sum << "\n";
Since, however, you only read the values from the file to add them together, you don't really need to store them at all. You could just add them together and print out the result:
cout << "The sum of the elements in the file is: "
<< std::accumulate(std::istream_iterator<int>(infile),
std::istream_iterator<int>(), 0);
The whole job reduced to one step...