Reading space separated input into an array in C++ - c++

What is the easiest way to read space separated input into an array?
//input:5
1 2 3 4 7
int main() {
int n;
cin>>n;
int array[n];
for (int i =0;i<n;i++){
cin>>array[i];
}
cout<<array;
return 0;
}
I tried the code above but the output is 0x7ffe42b757b0.

The problem lies with your printing. Since array is a pointer, you are only printing an address value.
Instead, do this:
for (int i =0;i<n;i++){
cout<< array[i] << " ";
}

You can do that by passing std::istream_iterator to std::vector constructor:
std::vector<int> v{
std::istream_iterator<int>{std::cin},
std::istream_iterator<int>{}
};
std::vector has a constructor that accepts 2 iterators to the input range.
istream_iterator<int> is an iterator that reads int from a std::istream.
A drawback of this approach is that one cannot set the maximum size of the resulting array. And that it reads the stream till its end.
If you need to read a fixed number of elements, then something like the following would do:
int arr[5]; // Need to read 5 elements.
for(auto& x : arr)
if(!(std::cin >> x))
throw std::runtime_error("failed to parse an int");

array variable always give base address of an array
for (int i =0;i<n;i++){
cout<< array[i] << " ";
cout<<*(array+i)<< " ";
}
Both cout statements will print same only.
in short
array[i] compiler will internally convert into *(array+i) like this only
in the second cout statement from base address of an array it won't add value,since it is an pointer it will add sizeof(int) each time for an increment

Related

how to divide an array into different arrays in c++

I have written this code in c++ to read a signal as an array and now I need to segment this array for 4 or 5 different arrays such that put first 20 elements in array1 ;20-50 in array2 and so on ..
how to do that in c++
my code :
int main()
{
// first we use for loop to insert the signal as arry by the user......
int size;
cout << "this programme read your signal as array first you need to "
"determine the size of the array "
<< endl
<< " Enter desired size of the array";
cin >> size;
vector<float> sig(size);
cout << "the signal " << endl;
for (int x = 0; x < size; x++)
{
cin >> sig[x];
}
}
To create a vector with a subrange of another vector you can use the constructor that takes two iterators( (5) in the link):
std::vector<float> x(100);
std::vector<flaot> y(x.begin()+begin,x.begin()+end);
y will have copies of elements from index begin till end (end not included) from x.
However, I would rather store the elements in the right place from the start instead of reading them into a vector<float> sig(size); first. Alternatively you can consider to keep all input in a single vector and pass iterators to functions that need to work with subranges of the full signal instead of splitting the signal.

Problem with forming string array using loop

I want to create a string array using loop inputs and then give ASCII based output for each character of the string.
Here is my code
int n;
cin >> n;
string arr[n];
for(int i=0;i<n;++i){
getline(cin,arr[i]);
}
for(int i = 0;i < n; ++i){
for(int j = 0;j < arr[i].length(); ++j){
cout << to_string(arr[i].at(j)) << " ";
}
cout << endl;
}
the program takes n : number of string inputs
but allows me to input only n-1 strings.
What is the problem here?
You are reading n strings, but the first one doesn't contain what you expect.
When you write input in the console, you write something like:
3\nstring1\nstring2
, where \n is the newline character (when you press Enter).
When you do cin >> n, you parse this input string, and you get the integer. Meaning that you remain with
\nstring1\nstring2
in the buffer. And when you do a getline, you parse everything up to the first newline (including the newline). That's why you get the first string empty.
A quick and dirty fix is to read the newline too:
int n;
char newline;
cin >> n >> newline;
, and then loop as you do now.
Some remarks about your code.
string arr[n] is not valid C++. In C++, there is no official support for arrays with variable size like this (some compilers support it, but this doesn't mean it's standard). You should use a std::vector:
std::vector<std::string> arr(n);
(the rest of the code remains the same). An even better way would be to declare it empty, and then use push_back to populate it.
Also, when comparing j < arr[i].length(), you are comparing a variable of type int with a variable of type size_t, which might be bigger than an int and create issues for very long strings. Use size_t as the type for j.
Use a std::vector
A vector is dynamic array. So change:
string arr[n];
to
std::vector<std::string> arr(n);
According to your code snippet what you want to read is a number of strings and then output for each of them the ASCII value of all of its characters:
If you have an input like the following
2
abc
def
you would like to obtains as a result something like the following:
97 98 99
100 101 102
In order to achieve that I see at least a couple of problems with your code.
C++ does not support variable size arrays by default. It means you cannot create an array whose size is not known at compile time (see this answer for more info about it)
In order to output the ASCII of the char you simply need to cast the char to int and that is it.
using getline in this case complicates the code because of the way getline works with newline. Simply use cin>>arr[i] to read each string.
Here is it a version of your code that does what you expect:
int n;
cin>>n;
vector<string> arr(n);
for(int i=0;i<n;++i)
cin>>arr[i];
for(const auto& s : arr){
for(const auto& c : s){
cout<<(int)c<<" ";
}
cout<<endl;
}
If you need a list of strings, you can use vector:
#include<vector>
#include<string>
int n;
cin >> n;
vector<string> arr(n);
for(int i = 0; i < n; ++i){
getline(cin, arr[i]);
}
for(auto& str : arr){
for(auto& c : str){
cout << to_string(c) << " ";
}
cout << endl;
}

User in a variable?

I am a beginner and I would like to ask you something.
We have an array whose size depends on value input by user in a variable ‘arraysize’. Look at below code and comments please, is it a correct way to achieve this said be behaviour?
int * myArray = NULL;
int arraySize;
cout << "Enter array size: ";
cin >> arraySize;
myArray = new int[arraySize];
delete [] myArray;
The earlier answer was a community wiki. Since you asked for an example, here's a more detailed answer.
A std::vector is a class belonging to the standard template library read in detail.
//since you used "using namespace std;" I'm omitting the "std::"
Declaration
vector< int > v; //creates a vector of integers
vector< double > vd; //vector of double values
This is quite similar to int a[/*any number*/].
Inserting values
v.push_back(5); //adds 5 to the end of the vector (or array of variable size)
With the above two lines you dont need to know in advance how many numbers you'll have to store.
One more sample code.
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector;
int myint;
std::cout << "Please enter some integers (enter 0 to end):\n";
do {
std::cin >> myint;
myvector.push_back (myint);
} while (myint);
std::cout << "myvector stores " << int(myvector.size()) << " numbers.\n";
return 0;
}
This program reads values and saves to myvector till 0 is entered in input.
Iteration
std::vector<int>::size_type sz = myvector.size(); //even int works here
// assign some values:
for (unsigned int i=0; i<sz; i++) myvector[i]=i;
Deletion
v.pop_back(); //removes last element
Use std::vector as a C++ best practice.

C++ file writing/reading

I'm trying to create an array, write array to the file and than display it. It seems to be working but i get just part of the output (first 3 elements) or i get values over boundaries.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int arr[20];
int i;
for (i = 0; i < 5; i++)
{
cout << "Enter the value to the array: " << endl;
cin >> arr[i];
}
ofstream fl("numbers.txt");
if (!fl)
{
cout << "file could not be open for writing ! " <<endl;
}
for (i = 0; i < arr[i]; i++)
{
fl<<arr[i]<<endl;
}
fl.close();
ifstream file("numbers.txt");
if(!file)
{
cout << "Error reading from file ! " << endl;
}
while (!file.eof())
{
std::string inp;
getline(file,inp);
cout << inp << endl;
}
file.close();
return 0;
}
The terminating condition in the for loop is incorrect:
for(i=0;i<arr[i];i++)
If the user enters the following 5 ints:
1 0 4 5 6
the for loop will terminate at the second int, the 0, as 1 < 0 (which is what i<arr[i] would equate to) is false. The code has the potential to access beyond the bounds of the array, for input:
10 11 12 13 14
the for loop will iterate beyond the first 5 elements and start processing unitialised values in the array arr as it has not been initialised:
int arr[20];
which could result in out of bounds access on the array if the elements in arr happen to always be greater than i.
A simple fix:
for(i=0;i<5;i++)
Other points:
always check the result of I/O operations to ensure variables contain valid values:
if (!(cin >> arr[i]))
{
// Failed to read an int.
break;
}
the for loop must store the number of ints read into the arr, so the remainder of the code only processes values provided by the user. An alternative to using an array, with a fixed size, and a variable to indicate the number of populated elements is to use a std::vector<int> that would contain only valid ints (and can be queried for its size() or iterated using iterators).
while (!file.eof()) is not correct as the end of file flag will set only once a read attempted to read beyond the end of the file. Check the result of I/O operations immediately:
while (std::getline(file, inp))
{
}
its like hmjd said
for(i=0;i<arr[i];i++)
looks wrong
it should look like this
int size;
size=sizeof(your array);
for(i=0;i<size;i++)
Try this:
//for(i=0;i<arr[i];i++)
for(i=0;i<5;i++)
[EDITED]
I would initialize the array with 0 like this: int arr[20] = {0}; In this case you can use for example:
while ((arr[i] != 0 || i < sizeof(arr))
i<array[i]
It is wrong beacuse it comapres with the content of the array ,it does not check the size of array .

Deleting duplicates in an array (C++)

I saw an older post on here asking how to do relatively the same thing, but their approach was different and i'm interested to know the hole in my program.
I am attempting to write a program that accepts characters into a 10 character length array. I want the program to evaluate the first array position and delete any duplicates it finds later in the array by identifying a duplicate and moving all of the values to the right of it to the left by one. The 'size' of the array is then decreased by one.
I believe the logic I used for the delete function is correct but the program only prints an 'a' for the first value and the fourth value in the array.
Any help would be greatly appreciated, here is my code:
#include <iostream>
using namespace std;
int letter_entry_print(int size, char array[10]);
int delete_repeats(int& size, char array[10]);
int final_array_print(int size, char array[10]);
int main()
{
char array[10];
int size = 10;
letter_entry_print(size,array);
delete_repeats(size,array);
final_array_print(size,array);
cout<<"\n";
system("pause");
}
int letter_entry_print(int size, char array[10])
{
int i;
for (i=0;i<size;i++)
{
cout << "Enter letter #" << i+1 << endl;
cin >> array[i];
cout << "\n";
}
cout << "\nYour array index is as follows:\n\n";
for (i=0;i<size;i++)
{
cout << array[i];
cout << " ";
}
cout <<"\n\n";
return 0;
}
int delete_repeats(int& size, char array[10])
{
int ans;
int loc;
int search;
int replace;
char target='a';
cout << "Enter 1 to delete repeats.\n\n";
cin >> ans;
if(ans==1)
{
for(loc=0;loc<size;loc++)
{
array[loc]=target;
for(search=1;search<(size-loc);search++)
{
if(target=array[loc+search])
{
for(replace=0;replace<(size-(loc+search));replace++)
{
array[loc+search+replace]=array[loc+search+replace+1];
array[size-1]=0;
size=(size-1);
}
}
}
}
}else(cout<<"\nWhy didn't you press 1?\n\n");
return 0;
}
int final_array_print(int size, char array[10])
{
cout<<"\nYour new index is as follows:\n\n";
int i;
for(i=0;i<size;i++)
{
cout<<array[i];
cout<<" ";
}
cout<<"\n";
return 0;
}
Ok, there are a few things about your code that look odd.
1) you repeat 10 all over the place to the point where there's no way you could resonably change it, but you also pass size along. Instead of making all your functions take arrays of 10 chars, consider just passing in a pointer to char, like:
int final_array_print(int size, char *array)
then you can change the size of your arrays more easily. There's no point in passing size everywhere if you're going to limit yourself forever to 10 items, and there's no good reason to pass arrays of 10 items around if you provide a size!
2) ok, so now you want to look for duplicates. Why do you overwrite the first element in your array with an 'a'?
char target='a';
...
array[loc]=target;
wouldn't you want to do it the other way around?
3) next, as #Mahesh points out, you probably want to use the comparison operator '==' rather than the assignment operator = when looking for duplicates that is:
if(target=array[loc+search])
should probably be
if(target == array[loc+search])
4) Next, dontbeafraidtousealittlewhitespacebetweenyourwordsandpunctuation.Itmakesitaloteasiertoidentifytypingmistakesandspellingerrors.
5) your loop to actually perform the replacement has incredibly complicated indices. It would be easier if you didn't start with replace = 0, but just start at replace = search + 1, try it out and perhaps you'll how much simpler all the rest of the indices become.