How to read n integers from standard input in C++? - c++

I need to read something like:
5 60 35 42
2 38 6
5 8
300 1500 900
And then save the first line in an array. After calling other functions do the same with the next line, and so on.
I try with gets() and then use sscanf() to scan the integers from the string, but I don't know how to read n numbers from a string.

C++
If you have an unknown number of entries spread across an unknown number of lines, ending at EOF:
int n;
while(cin >> n)
vector_of_int.push_back(n);
If you have a known number of entries spread across an unknown number of lines:
int n;
int number_of_entries = 20; // 20 for example, I don't know how many you have.
for(int i ; i < number_of_entries; ++i)
if(cin >> n)
vector_of_int.push_back(n);
If you have an uknown number of entries on a single line:
std::string str;
std::getline(std::cin, str);
std::istringstream sstr(str);
int n;
while(sstr >> n)
vector_of_int.push_back(n);
If you have a unknown number of entries spread across a known number of lines:
for(int i = 0; i < number_of_lines; ++i) {
std::string str;
if(std::getline(std::cin, str)) {
std::istringstream sstr(str);
int n;
while(sstr >> n)
vector_of_int.push_back(n);
}
}

I've seen input files like this for competitions before. If speed is more of an issue than error detection, you could use a custom routine. Here's one similar to that I use:
void readintline(unsigned int* array, int* size) {
char buffer[101];
size=0;
char* in=buffer;
unsigned int* out=array;
fgets(buffer, 100, stdin);
do {
*out=0;
while(*in>='0') {
*out= *out* 10 + *in-'0';
++in;
}
if (*in)
++in; //skip whitespace
++out;
} while(*in);
size = out-array;
}
It will destroy your memory if there's more than 100 characters on a line, or more numbers than array can hold, but you won't get a faster routine to read in lines of unsigned ints.
On the other hand, if you want simple:
int main() {
std::string tmp;
while(std::getline(std::cin, tmp)) {
std::vector<int> nums;
std::stringstream ss(tmp);
int ti;
while(ss >> ti)
nums.push_back(ti);
//do stuff with nums
}
return 0;
}

I'd probably write the code something like this:
// Warning: untested code.
std::vector<int> read_line_ints(std::istream &is) {
std::string temp;
std::getline(is, temp);
std::istringstream buffer(temp);
int num;
std::vector<int> ret;
while (buffer>>num)
ret.push_back(num);
return ret;
}

In C++, you can use std::istringstream.
std::string nums = "1 20 300 4000";
std::istringstream stream(nums);
int a, b, c, d;
stream >> a >> b >> c >> d;
assert(a == 1 && b == 20 && c == 300 && d == 4000);
If you want to get it from the standard input, then do the same, but just use std::cin
std::cin >> a >> b >> c >> d;

The quick solution is to read them with scanf()
int array[1000];
int index = 0;
while ((index < 1000) && (scanf("%d", &tmp) == 1)) {
array[index++] = tmp;
}
This still needs a bit more validation ...

C++:
vector<int> ints;
while( !cin.eof() )
{
int t;
cin >> t;
if ( !cin.eof() )
ints.push_back(t);
}
Alternative (thx to Shahbaz)
int t;
vector<int> ints;
while(cin >> t)
ints.push_back(t);

In C++ it's extremely simple to read N integers separated by whitespace via stdin:
#include <iostream>
using namespace std;
const unsigned N = 5;
int main(void)
{
int nums[N];
for (unsigned i = 0; i < N; ++i)
cin >> nums[i];
cout << "Your numbers were:\n";
for (unsigned i = 0; i < N; ++i)
cout << nums[i] << " ";
cout << "\n";
return 0;
}

Related

How to know the number of digits in an integer

I'm new to programming, and I'm wondering, how can I know the number of digits in an integer that the user enters? For example: the user enters a number like 123456, how can I know that the user enters 6 digits? I don't want to use a for loop to get user input because I don't want the user to enter each digit after a space or enter.
Right now, I'm converting a number to an array of digits so I can have control over them, but the issue is that I don't know how many digits I should loop over, because I don't know how many digits are in the number.
Can I get the user's input as a string and then use string.length and convert it to an array of digits?
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
while(N--)
{
int num;
cin >> num;
int arr[1000];
for (int i=0 ;i<???;i++)
{
arr.[i]=num%10;
num = num /10;
}
}
}
an easier way to do this is to convert it to a string then count the length of said string
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
string str = to_string(n);
cout <<"the length of" <<str << "is:" <<str.length() <<"\n";
}
typing in a 41 will print out.
the length of 41 is 2
while (num != 0)
{
arr.[i]=num%10;
num = num /10;
}
is a common pattern that's close to what you already have.
Although you can do what you mentioned in your question and someone suggested in the comments and get the input as a string and use string.length.
Yes, you can read in the user's input as a std::string instead of as an int, and then you can use std::string::size() (or std::string::length()) to get the number of characters in the string, eg:
#include <iostream>
#include <string>
int main()
{
std::string S;
std::cin >> S;
int arr[1000] = {};
for (size_t i = 0; i < S.size(); ++i)
{
arr[i] = (S[i] - '0');
}
return 0;
}
Alternatively:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string S;
std::cin >> S;
int arr[1000] = {};
std::transform(S.begin(), S.end(), arr, [](char ch){ return int(ch - '0'); });
return 0;
}
Either way, if needed, you can check if the std::string represents a valid integer using std::stoi() or std::strtol() or other similar function, or by putting the std::string into a std::istringstream and then reading an integer from it.
Otherwise, you can read the user's input as an int and then convert it to a std::string for processing:
#include <iostream>
#include <string>
int main()
{
unsigned int N;
std::cin >> N;
std::string S = std::to_string(N);
int arr[1000] = {};
for (size_t i = 0; i < S.size(); ++i)
{
arr[i] = (S[i] - '0');
}
// or:
// std::transform(S.begin(), S.end(), arr, [](char ch){ return int(ch - '0'); });
return 0;
}
Otherwise, if you really want to read in an int and loop through its digits directly, you can use something more like this:
#include <iostream>
int main()
{
unsigned int N;
std::cin >> N;
int arr[1000] = {};
size_t i = 0;
while (N != 0)
{
arr[i++] = num % 10;
num /= 10;
}
return 0;
}

How to print long int to the screen in c++?

I am trying to return long int from a function but it is not working at all, then I tried to print a long int number to the screen and still not working.
#include<iostream>
using namespace std;
long int maximum_product(long int *input_array, int n){
long int a,b;
a = *input_array;
b = *(input_array + 1);
if (b > a){
long int temp = a;
a = b;
b = temp;
}
for (int i = 2; i < n; i++){
if (input_array[i] > b){
if(input_array[i] > a){
b = a;
a = input_array[i];
} else
b = input_array[i];
}
}
return a * b;
}
int main(){
int n;
cin >>n;
long int *input_array = new long int[n];
for (int i = 0; i < n; i++)
cin >> input_array[i];
cout << maximum_product(input_array, n);
return 0;
}
Here is what I mean by "not working":
#include<iostream>
using namespace std;
int main(){
long int y;
cin >>y;
cout<<y;
return 0;
}
Result of the second program
If you want to make std::cin read
2,147,483,646
as a long you need to do a little bit extra, because without you std::cin will only read the first 2 and ignore the rest.
Lets start simple....std::cin has an overload of its operator>> for long but we want it to do something else. How do we make it pick a different overload? We pass a different type. However, as we dont actually want anything else than a long we use a thin wrapper:
struct read_long_with_comma_simple_ref {
long& long;
read_long_with_comma_simple_ref(long& value) : value(value) {}
};
Once we supply our own operator>> overload we will be able to write something like this:
long x;
std::cin >> read_long_with_comma_simple_ref(x);
So far so simple. How can we implement that operator>>? The most simple I can think of is to simply ignore the commas:
std::istream& operator>>(std::istream& in,read_long_with_comma_simple_ref& ref) {
std::string temp;
// read till white space or new-line
in >> temp;
// remove all commas
temp.erase(std::remove(temp.begin(), temp.end(), ','), temp.end());
// use a stringstream to convert to number
std::stringstream ss(temp);
ss >> rwcs.value;
return in;
}
However, this will accept non-sense such as 12,,,34 as input and interpret it as 1234. This we of course want to avoid and add a bit of error checking:
#include <iostream>
#include <limits>
#include <algorithm>
#include <sstream>
#include <ios>
// same as before, just different name for a different type
struct read_long_with_comma_ref {
long& long;
read_long_with_comma_ref(long& value) : value(value) {}
};
std::istream& operator>>(std::istream& in,read_long_with_comma_ref&& rwc){
std::string temp;
in >> temp;
std::reverse(temp.begin(),temp.end());
std::stringstream ss(temp);
rwc.value = 0;
long factor = 1;
for (int i=0;i<temp.size();++i){
char digit;
ss >> digit;
if (((i+1)%4)==0) {
if (digit != ',') {
in.setstate(std::ios::failbit);
rwc.value = 0;
return in;
}
} else {
int dig = digit - '0';
if (dig < 0 || dig > 9) {
in.setstate(std::ios::failbit);
rwc.value = 0;
return in;
}
rwc.value += factor* (digit-'0');
factor*=10;
}
}
return in;
}
And we can use it like this:
long x;
std::cin >> read_long_with_comma_ref(x);
if (std::cin.fail()) std::cout << "reading number failed \n";
std::cout << x;
TL;DR if you want to make std::cin read the value 2147483646 then simply type 2147483646 and dont use the , as seperator, or read it as string and remove the commas before converting it to a number.

C++ determinable array input in one line

I'm pretty new to c++ and can't seem to find correct way to code this. I have array of n digits, my code now:
int main()
{
int n,i;
cin >> n;
int a[n];
for (i=1;i<=n;i++)
{
cin >> a[i];
}
return 0;
}
This way every element of array has to be input in different line, is it possible to put all elements of a array in one line, with space between them.
I am assuming your question is "what is the correct way to do this?"
I would do it this way:
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
int main()
{
int n;
cin >> n;
vector<int> v;
int i = 0;
int value;
while (i++ < n && cin >> value)
{
v.push_back(value);
}
char const* sep = "";
for (auto item : v)
{
cout << sep << item;
sep = " ";
}
cout << endl;
}
Note that this code is making assumptions that the input is well formed. If you need something that is more robust in handling possibly malicious input, that would require extra effort. This code, as given, will give-up-trying-and-continue which may or may not be suitable for your purposes.
The following code snippet of your program is a Variable Length Array(VLA) and this is only supported in C since ISO C99.
cin >> n;
int a[n];
And as previously pointed out, you can also use std::vector instead.
int main()
{
int size;
std::cin >> size;
int *array = new int[size];
delete [] array;
return 0;
}
References:
http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html
How to create a dynamic array of integers
Without using stl container , one can implement like so:
#include <iostream>
#include <string>
#include "stdlib.h"
void GetInput(int* inputs, int n)
{
// store the entered numbers in a char[]
std::string word;
std::cout << "enter numbers (separate by space) ";
std::getline(std::cin, word);
char ch[100];
strcpy_s(ch, word.c_str());
char *temp = ch;
// parse the char[] for integers
for (int i = 0; strcmpi(temp, "") != 0 && i <= n; temp++,i++) {
*(inputs +i) = std::strtol(temp, &temp, 10);
}
}
int main()
{
int n = 3;
int inputs[10];
GetInput(inputs,n);
for (int j = 0; j < n; j++)
std::cout << inputs[j] << " \n";
return 0;
}
Output:

How cast char to int in C++? (File Handling)

Lets say I have a txt file list.txt
The txt file has list of integers ,
88
894
79
35
Now I am able to open the file and display the contents in it but not able to store it in an integer array.
int main()
{
ifstream fin;
fin.open("list.txt");
char ch;
int a[4],i=0;
while((!fin.eof())&&(i<4))
{
fin.get(ch);
a[i]=(int)ch;
cout<<a[i]<<"\n";
i++;
}
fin.close();
return 0;
}
Please help!!
You can use >> to read text-formatted values:
fin >> a[i]
You should check for the end of the file after trying to read, since that flag isn't set until a read fails. For example:
while (i < 4 && fin >> a[i]) {
++i;
}
Note that the bound needs to be the size of the array; yours is one larger, so you might overrun the array if there are too many values in the file.
Try the following
#include <iostream>
#include <fstream>
int main()
{
const size_t N = 4;
int a[N];
std::ifstream fin( "list.txt" );
size_t i = 0;
while ( i < N && fin >> a[i] ) i++;
while ( i != 0 ) std::cout << a[--i] << std::endl;
return 0;
}

C++: Read string from cin stream and store values separated by space

Actually I came up with (temporary) solution but I still think it could've been done more efficient, but how? Im not quite familiar with streams (still a C++ beginner). My point is to read line from std::cin stream using std::getline() (I assumed that it can be only read as string) so I tried to set some std::string::const_iterator and iterate over each char my string contains using ' ' as a delimiter to distinguish different words (values) in my string. I will read only two integers separated by single space.
Example:
Input:
2 (the number of cases)
10 20
30 40
Result:
Store 10 in variable A, 20 in variable B, 30 in variable C... etcetera.
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main()
{
bool next;
unsigned short int cases;
long long m, n;
std::vector<long long> vcases;
std::string m_n_store;
std::string m_n_read;
std::cin >> cases;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
for (int i = 0; i < cases; ++i)
{
next = false;
std::getline(std::cin, m_n_read);
for (std::string::const_iterator it = m_n_read.begin(); it != m_n_read.end(); ++it)
{
if (*it == ' ')
{
next = true;
std::istringstream iss(m_n_store);
iss >> m;
vcases.push_back(m);
m_n_store.erase();
}
if (!next) m_n_store.push_back(*it);
else if (*it != ' ') m_n_store.push_back(*it);
if (it == (m_n_read.end() - 1))
{
std::istringstream iss(m_n_store);
iss >> n;
vcases.push_back(n);
m_n_store.erase();
};
}
}
for (int i = 0; i < vcases.size(); ++i)
{
std::cout << vcases[i] << '\n';
}
}
C++ streams, by default, delimit input operations by whitespace. There's no need to iterate through a string and break it by the space character. You can use std::istream_iterator and the range constructor of the vector instead:
std::vector<long long> mcases{std::istream_iterator<long long>{std::cin}, {}};
Try this:
size_t pos = 0;
while ((pos = m_n_read.find(" ")) != std::string::npos) {
std::istringstream iss(m_n_read.substr(0, pos));
iss >> m;
vcases.push_back(m);
m_n_read.erase(0, pos + 1);
}
if (m_n_read.size() > 0)
{
std::istringstream iss(m_n_read);
iss >> m;
vcases.push_back(m);
}