C++ cin read STDIN - c++

How to use C++ to get all the STDIN and parse it?
For example, my input is
2
1 4
3
5 6 7
I want to use C++ to read the STDIN using cin and store the each line in an array. So, it will be an vector/array of array of integers.
Thanks!

Since this isn't tagged as homework, here's a small example of reading from stdin using std::vectors and std::stringstreams. I added an extra part at the end also for iterating through the vectors and printing out the values. Give the console an EOF (ctrl + d for *nix, ctrl + z for Windows) to stop it from reading in input.
#include <iostream>
#include <vector>
#include <sstream>
int main(void)
{
std::vector< std::vector<int> > vecLines;
// read in every line of stdin
std::string line;
while ( getline(std::cin, line) )
{
int num;
std::vector<int> ints;
std::istringstream ss(line); // create a stringstream from the string
// extract all the numbers from that line
while (ss >> num)
ints.push_back(num);
// add the vector of ints to the vector of vectors
vecLines.push_back(ints);
}
std::cout << "\nValues:" << std::endl;
// print the vectors - iterate through the vector of vectors
for ( std::vector< std::vector<int> >::iterator it_vecs = vecLines.begin();
it_vecs != vecLines.end(); ++it_vecs )
{
// iterate through the vector of ints and print the ints
for ( std::vector<int>::iterator it_ints = (*it_vecs).begin();
it_ints < (*it_vecs).end(); ++it_ints )
{
std::cout << *it_ints << " ";
}
std::cout << std::endl; // new line after each vector has been printed
}
return 0;
}
Input/Output:
2
1 4
3
5 6 7
Values:
2
1 4
3
5 6 7
EDIT: Added a couple more comments to the code. Also note that an empty vectors of ints can be added to vecLines (from an empty line of input), that's intentional so that the output is the same as the input.

int main ()
{
char line[100];
while(!cin.eof()){
cin.getline(line, 100);
printf("%s\n", line);
}
return 0;
}
Sorry, I just wasn't sure if there's any way better than this.

This one should fit your requirement , use istringstream to separate the line into an array.
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string s("A B C D E F G");
vector<string> vec;
istringstream iss(s);
do
{
string sub;
iss >> sub;
if ( ! sub.empty() )
vec.push_back (sub);
} while (iss);
vector<string>::iterator it = vec.begin();
while ( it != vec.end() )
{
cout << *it << endl;
it ++;
}
return 0;
}

Related

How to user input the array elements in c++ in one line

I am new to c++ , Basically I belong to PHP . So I am trying to write a program just for practice, to sort an array . I have successfully created the program with static array value that is
// sort algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector
bool myfunction (int i,int j) { return (i<j); }
struct myclass { bool operator() (int i,int j) { return (i<j);} } myobject;
int main () {
int myints[] = {55,82,12,450,69,80,93,33};
std::vector<int> myvector (myints, myints+8);
// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4);
// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction);
// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject);
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
its output is ok . But I want that the elements should input from user with space separated or , separated . So i have tried this
int main () {
char values;
std::cout << "Enter , seperated values :";
std::cin >> values;
int myints[] = {values};
/* other function same */
}
it is not throwing an error while compiling. But op is not as required . It is
Enter , seperated values :20,56,67,45
myvector contains: 0 0 0 0 50
3276800 4196784 4196784
------------------ (program exited with code: 0) Press return to continue
You can use this simple example:
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
stringstream ss;
string str;
getline(cin, str);
replace( str.begin(), str.end(), ',', ' ');
ss << str;
int x = 0;
while (ss >> x)
{
cout << x << endl;
}
}
Live demo
or, if you want to have it more generic and nicely enclosed within a function returning std::vector:
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
using namespace std;
template <typename T>
vector<T> getSeparatedValuesFromUser(char separator = ',')
{
stringstream ss;
string str;
getline(cin, str);
replace(str.begin(), str.end(), separator, ' ');
ss << str;
T value{0};
vector<T> values;
while (ss >> value)
{
values.push_back(value);
}
return values;
}
int main()
{
cout << "Enter , seperated values: ";
auto values = getSeparatedValuesFromUser<int>();
//display values
cout << "Read values: " << endl;
for (auto v : values)
{
cout << v << endl;
}
}
Live demo
Read in all the values into one string, then use a tokenizer to separate out the individual values.
How do I tokenize a string in C++?
The above answers are very good for an arbitrary number of inputs, but if you allready know how many numbers will be put, you could do it like:
int[5] intList;
std::cin >> intList[0] >> intList[1] >> intList[2] >> intList[3] >> intList[4]
But please note that this method does not do any check if the numbers are put properly, so if there are for example letters or special characters in the input, you might get unexpected behavior.
Let's see what you wrote:
int main () {
char values;
std::cout << "Enter , seperated values :";
std::cin >> values; // read a single character
int myints[] = {values}; // create a static array of size 1 containing the single character converted to an int
/* other function same */
}
what you need is:
#include <sstream>
#include <string>
...
int main () {
std::cout << "Enter space seperated values :";
std::vector<int> myvector;
std::string line;
std::getline(std::cin, line); // read characters until end of line into the string
std::istringstream iss(line); // creates an input string stream to parse the line
while(iss >> value) // so long as values can be parsed
myvector.push_back(value); // append the parsed value to the vector
/* other function same */
}
If you want comma separated input you'll need to parse the comma as a single character in addition to the integer values.
What you are doing
int main () {
char values; //Declare space for one character
std::cout << "Enter , seperated values :"; //Ask user to enter a value
std::cin >> values; //Read into values (one value only)
int myints[] = {values}; // assign the first element to the ASCII code of whatever user typed.
/* other function same */
}
In the language char works as an 8-bit integer. Through function overloading, different behavior can be implemented. Read about static polymorphism for more details how it works.
What you need to do
std::vector<int> values;
char ch_in;
std::string temp;
while(cin.get(ch_in)) {
switch(ch_in) {
case ',':
case ' ': //Fall through
values.push_back(atoi(temp.c_str()); //include cstdlib for atoi
temp.clear();
break;
default:
temp+=ch_in;
}
}
You should put this in a separate function. With this skeleton, you can implement a more fancy syntax by adding more cases, but then you need something else than a std::vector<int> to put things into. You can (should?) also add error checking in the default case:
default:
if( (ch_in>='0' && ch_in<='9')
|| (temp.size()==0 && ch_in=='-') ) {
temp+=ch_in;
}
else {
cerr<<ch_in<<" is an illegal character here."
temp.clear();
}
#include <iostream>
#include <string>
#include <sstream>
#include <string.h>
using namespace std;
// THIS CODE IS TO GIVE ARRAY IN ONE LINE AND OF DESIRED LENGHT ALSO WITH NEGATIVE NUMBERS
// You can also do it by using ASCII but we Are using library name
// <sstream> to convert string charters to numbers
//O(n) time complexity
int main()
{
/*
// INPUT
// 7 array length
// 34-56-789 // without space b/w them */
int N;
cout << "Enter the size of the array " << endl;
cin >> N;
cout << "INPUT Without giving space b/w " << endl;
string strx;
cin >> strx;
int X[N]; // array to store num
int p = 0;
// NOTE USE HERE STRX.LENGHT() becouse we have to go through the whole string
for (int i = 0; i < strx.length(); i++)
{ // we have declare tempx to store a particular character
// one time
string tempx;
tempx = strx[i];
stringstream strtointx(tempx);
// this is the syntax to convert char to int using <sstream>
if (strx[i] == '-')
{
/*
The tricky point is when you give string as 1-23
here - and 2 are the separte characters so we are not
getting -2 as number but - and 2 so what we do is
we chek for '-' sign as the character next to it
will be treated as negative number
*/
tempx = strx[i + 1];
// by assigning strx[i+1] to tempx so that we can getting the which should be treated as negative number
stringstream strtointx(tempx);
// still it is a charter type now again using library
// convert it to int type
strtointx >> X[p];
X[p] = -X[p];
// now make that number to negative ones as we want it to be negative
i++;
// inside this if i++ will help you to skip the next charcter of string
// so you can get desired output
}
// now for all the positive ones to int type
else{ strtointx >> X[p]; }
p++; // finally increment p by 1 outside if and else block
}
// loop ends now get your desired output
cout<<"OUTPUT "<<endl;
for (int i = 0; i < N; i++)
{
cout << X[i] << " ";
}
cout<<endl;
cout<<"CODE BY MUKUL RANA NIT SGR Bch(2020)";
return 0;
}
// OUTPUT
/*
Enter the size of the array
7
INPUT Without giving space b/w
34-56-789
OUTPUT
3 4 -5 6 -7 8 9
CODE BY MUKUL RANA NIT SGR Bch(2020)
PS C:\Users\user\Desktop\study c++>
*/
// CAUTION :
/*
1) do not give input with spaces
**** if you do then first you have to change /chek the code for spaces indexes also ***
2)do not give charates as 56-89##13 as you want here only numbers
3) this only for integer if you want to float or double you have to do some changes here
because charters index and length would be difeerent in string.
*/

C++ Read from file and assign to a variables

i have a question.
I have a file in format like this:
A B
C D
E F
X Y
X2 Y2
X3 Y3
I know how to assign A,B,C,D,E,F,X,Y (each file i check have this data) but sometimes i have more data like X2 Y2, X3, Y3 and i want to assing these also (without previous knowledge about how many of these are in the file).
Actually my code looks like this:
reading >> a >> b >> c >> d >> e >> f >> x >> y;
Could You help me? Thank You
This solution with vectors might solve the problem:
#include <vector>
#include <string>
#include <iterator>
#include <iostream>
#include <fstream>
using namespace std;
void getItems(vector<string>& v, string path)
{
ifstream is(path.c_str());
istream_iterator<string> start(is), end;
vector<string> items(start, end);
v = items;
}
int main()
{
vector<string> v;
getItems(v, "C:\test.txt");
vector<string>::iterator it;
for (it = v.begin(); it != v.end(); it++)
cout << *it << endl;
return 0;
}
Note: here i am assuming that your file is in C:\test.txt
You can input all of them as a string. Give the header as #input and use gets() function to input the entire input. Then work on the string. You can differentiate between the numbers by neglecting space(" ") and new lines ("\n").
Hope this helps!
You can use 2D vector:
Input:
1 2 3
4 5
6
7 8 9
Code:
int val;
string line;
ifstream myfile ("example.txt");
vector<vector<int> > LIST;
if (myfile.is_open())
{
while ( getline(myfile,line) )
{
vector<int> v;
istringstream IS(line);
while( IS >> val)
{
v.push_back(val);
}
LIST.push_back(v);
}
myfile.close();
}
for(int i=0; i<LIST.size(); i++)
{
for(int j=0; j<LIST[i].size(); j++)
{
cout << LIST[i][j] << " ";
}
cout << endl;
}
Output:
1 2 3
4 5
6
7 8 9
In the case where you don't know how much data is in the file, it is worth to use a
WHILE loop with the condition that you perform the while loop until it reaches the end of the file.
Something like this (ensure you include: iostream, fstream, and string):
int main () {
string line;
ifstream thefile ("test.txt");
if (thefile.is_open())
{
while (thefile.good() )
{
getline (thefile, line);
}
thefile.close();
}
else
{
cout << "Unable to open\n";
}
return 0;
}
If I understood you well you want to be sure that all lines in the file must be read.
With the following code I solved the problem for me:
std::ifstream file_reading( filename_path_.c_str(), std::ios::in );
if( file_reading ) {
std::string buffer;
unsigned int line_counter = 0;
while( std::getline( file_reading, buffer ) ) {
std::istringstream istr;
istr.str( buffer );
if( buffer.empty() )
break;
istr >> x_array[local_counter] >> y_array[local_counter];
line_counter++;
}
}
using getline and a while loop you all get all lines in the file and store them in a std::vector which is resizable.
The instruction break will quit if no more data are found in the next line.

C++ how to get ONLY integers from complex string

I have few strings, each one contains one word and several integer numbers (One string is whole line):
Adam 2 5 1 5 3 4
John 1 4 2 5 22 7
Kate 7 3 4 2 1 15
Bill 2222 2 22 11 111
As you can see, each word/number is separated with space. Now, I want to load these data into a map, where word (name) would be the key and the value would be vector of the numbers in line. I already have key values in separated temporary stl container, so the task is to load only the integer numbers from each line to 2D vector and then merge these two into map.
The question is, is there any C++ function, which would avoid words and white spaces and get only integers from a string, or I have to search strings char-by-char like
here ?
I found only partial solution, which is not able to get more than one digit number:
vector<int> out;
for (int i = 0; i < line.length(); i++) {
if (isdigit(line.at(i))) {
stringstream const_char;
int intValue;
const_char << line.at(i);
const_char >> intValue;
out.push_back(intValue);
}
}
If every line has the format "word number number number ...", use a stringstream and skip the word by reading it.
If the current line is in line:
vector<int> out;
istringstream in(line);
string word;
in >> word;
int x = 0;
while (in >> x)
{
out.push_back(x);
}
split the string on spaces since that seems to be your delimiter. Then check that each substring contains an int with strol.
Then use stoi to convert the integer substrings to int.
If no stoi conversion can be performed (the string does not contain a number), an invalid_argument exception is thrown, so don't try to convert the name substring.
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <cstdlib>
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
inline bool isInteger(const std::string & s)
{
if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false ;
char * p ;
strtol(s.c_str(), &p, 10) ;
return (*p == 0) ;
}
int main()
{
std::cout << "Hello World" << std::endl;
std::string example="Adam 2 5 1 5 3 4";
std::vector<std::string> subStrings;
subStrings = split(example, ' ');
std::string sItem;
for(std::vector<std::string>::iterator it = subStrings.begin(); it != subStrings.end(); ++it) {
sItem = *it;
if( isInteger(sItem) ){
int nItem = std::stoi (sItem);
std::cout << nItem << '\n';
}
}
return 0;
}
use find() and substr() of string Class to find the name if it is always at the beginning of the string.
std::string s = "Adam 2 5 1 5 3 4";
std::string delimiter = " ";
s.substr(0, s.find(delimiter)); //To get the name
s.erase(0, s.find(delimiter)); //To delete the name
//Repeat the mechanism with a for or a while for the numbers
I do not test this solution but I use something similar with always the label in first place.
If the name could be anywhere, I do not see how test it without check for every character.
Here is a program that demonstrates an approach to the task that can be used.
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <iterator>
int main()
{
std::string s( "Adam 2 5 1 5 3 4" );
std::map<std::string, std::vector<int>> m;
std::string key;
std::istringstream is( s );
if ( is >> key )
{
m[key] = std::vector<int>( std::istream_iterator<int>( is ),
std::istream_iterator<int>() );
}
for ( const auto &p : m )
{
std::cout << p.first << ": ";
for ( int x : p.second ) std::cout << x << ' ';
std::cout << std::endl;
}
return 0;
}
The output is
Adam: 2 5 1 5 3 4
Assuming that the name comes first, here is a function that will read the string and add to the map.
#include <map>
#include <vector>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;
typedef std::map<std::string, std::vector<int> > StringMap;
void AddToMap(StringMap& sMap, const std::string& line)
{
// copy string to stream and get the name
istringstream strm(line);
string name;
strm >> name;
// iterate through the ints and populate the vector
StringMap::iterator it = sMap.insert(make_pair(name, std::vector<int>())).first;
int num;
while (strm >> num)
it->second.push_back(num);
}
The function above adds a new entry to the map with the first read, and on subsequent reads, populates the vector.
Note that the map::insert function returns a std::pair, where the first of that pair is the iterator to the map entry that was created. So we just get the iterator, and from there, push_back the entries.
Here is a test program:
int main()
{
vector<std::string> data = { "Adam 2 5 1 5 3 4", "John 1 4 2 5 22 7",
"Kate 7 3 4 2 1 15", "Bill 2222 2 22 11 111" };
StringMap vectMap;
// Add results to map
for_each(data.begin(), data.end(),
[&](const std::string& s){AddToMap(vectMap, s); });
// Output the results
for_each(vectMap.begin(), vectMap.end(),
[](const StringMap::value_type& vt)
{cout << vt.first << " "; copy(vt.second.begin(), vt.second.end(),
ostream_iterator<int>(cout, " ")); cout << "\n"; });
}
Live example: http://ideone.com/8UlnX2

How to use cin with a variable number of inputs?

I was in a programming competition yesterday and we had to read in input of the form
n
a1 a2 ... an
m
b1 b2 ... bm
...
where the first line says how many inputs there are, and the next line contains that many inputs (and all inputs are integers).
I know if each line has the same number of inputs (say 3), we can write something like
while (true) {
cin >> a1 >> a2 >> a3;
if (end of file)
break;
}
But how do you do it when each line can have a different number of inputs?
Here's a simple take using just standard libraries:
#include <vector> // for vector
#include <iostream> // for cout/cin, streamsize
#include <sstream> // for istringstream
#include <algorithm> // for copy, copy_n
#include <iterator> // for istream_iterator<>, ostream_iterator<>
#include <limits> // for numeric_limits
int main()
{
std::vector<std::vector<double>> contents;
int number;
while (std::cin >> number)
{
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip eol
std::string line;
std::getline(std::cin, line);
if (std::cin)
{
contents.emplace_back(number);
std::istringstream iss(line);
std::copy_n(std::istream_iterator<double>(iss), number, contents.back().begin());
}
else
{
return 255;
}
}
if (!std::cin.eof())
std::cout << "Warning: end of file not reached\n";
for (auto& row : contents)
{
std::copy(row.begin(), row.end(), std::ostream_iterator<double>(std::cout," "));
std::cout << "\n";
}
}
See it live on Coliru: input
5
1 2 3 4 5
7
6 7 8 9 10 11 12
Output:
1 2 3 4 5
6 7 8 9 10 11 12
you can do it this way
#include<vector>
...
...
std::vector<sometype> a;
sometype b;
std::cin >> b;
while(std::cin)
{
a.push_back(b);
std::cin >> b;
}
you can input any number of items and when you are finished send in the EOF signal.
Your Algorithm will look something like this:
1. read the 'number' of inputs, say n1
2. set up a loop to read the n1 inputs
3. check if the user has more inputs to give
if YES repeat the steps 1,2 and 3 till all inputs are taken and stored.
else move on...
You can use a for or while loop and store the inputs into an array.
Hope this helps!
Because people were complaining how I called my first answer "a simple take", here's a proper version using Boost Spirit:
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
int main()
{
typedef std::vector<std::vector<double>> data_t;
typedef boost::spirit::istream_iterator It;
std::cin.unsetf(std::ios::skipws);
It first(std::cin), last;
bool ok;
data_t contents;
{
using namespace boost::spirit::qi;
static rule<It, data_t(), blank_type, locals<int>> file;
static rule<It, std::vector<double>(int number), blank_type> row;
_a_type number; // friendly alias
file %= -(omit [int_[number=_1]] > eol > row(number)) % eol;
row = repeat(_r1) [ double_ ];
ok = phrase_parse(first, last, file, blank, contents);
}
if (ok) for (auto& row : contents)
{
std::copy(row.begin(), row.end(), std::ostream_iterator<double>(std::cout," "));
std::cout << "\n";
}
if (first!=last)
std::cout << "Warning: end of file not reached, remaining unparsed: '" << std::string(first, last) << "'\n";
}
It's obviously far superior
it uses far fewer include lines :)
it takes ~10x as long to compile (with no optimizations), another 16% longer with optimizations
it requires about 5 years of study in meta-programming to grok it (joking, the spirit docs/tutorials are quite ok)
on the serious account: it is much more flexible
can be extended to parse other structural elements, more complicated
can implement semantics on the fly
will parse NaN and +/-infinity correctly
etc.
See it Live on Coliru as well
Given the format you are specifying, here is what I would do.
for (int n; std::cin >> n; )
{
if (n == 0) // Test for end of input
break;
for (int i = 0; i != n; ++i)
{
int x;
std::cin >> x;
if (!std::cin)
break;
// Valid input x. Now do something with x like
// v.push_back(x) where v is some vector of ints
}
}
// Did we succeed?
if (!std::cin)
{
// Something went bad.
std::cerr << "Error reading input" << std::endl;
return EXIT_FAILURE;
}
Simple, use a for loop and array.
int a[MAX]; // programming problems usually specify a max size
for(i=0;i<n;i++)
cin>>a[i];
A simple solution using arrays and dynamic memory allocation for taking variable number of inputs of a predefined type.
#include<iostream>
using namespace std;
int main(){
int n;
cout<<"Enter the number of elements"<<endl;
cin>>n;
int *c=new int[n];
for(int k=0;k<n;k++)
cin>>c[k];
delete c;
}

reading data file into 2d array c++

I have a text file with 2 columns and many rows. each column is separated by spaces. i need to read them to a 2D array for further calculations.
my data file looks like
0.5 0.479425539
1 0.841470985
1.5 0.997494987
2 0.909297427
2.5 0.598472144
3 0.141120008
3.5 -0.350783228
4 -0.756802495
4.5 -0.977530118
5 -0.958924275
And my feeble attempt is
#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <ctype.h>
using namespace std;
int main () {
char line,element;
std::ifstream myfile ("C:\\Users\\g\\Desktop\\test.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline(myfile,line);
cout << line<<endl;
_getch();
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
The problem is I'm not able to read them correctly.... its either reading the whole line... if I specify the delimiter as 'space' then, its not reading the next row.
Pls point out whats wrong. and what should i do to store the data into 2d array for further calculations.
Thank you
#include <fstream>
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
int main(int argc, char** argv) {
std::ifstream f(argv[1]);
std::string l;
std::vector<std::vector<double> > rows;
while(std::getline(f, l)) {
std::stringstream s(l);
double d1;
double d2;
if(s >> d1 >> d2) {
std::vector<double> row;
row.push_back(d1);
row.push_back(d2);
rows.push_back(row);
}
}
for(int i = 0; i < rows.size(); ++i)
std::cout << rows[i][0] << " " << rows[i][1] << '\n';
}
The last for loop shows how to use the values in the "array". The variable rows is strictly speaking not an array, but a vector of vectors. However, a vector is much safer than c-style arrays, and allows access to its elements using [].
[As I posted this I saw a very similar program posted as a response. I wrote mine independently.]
You can read the whole line into a std::string, then use std::istringstream to extract the values from the line.
A complete working program:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
int main()
{
std::ifstream file("C:\\Users\\g\\Desktop\\test.txt");
std::string line;
// Read a line of input from the file
while (std::getline(file, line))
{
// `istringstream` behaves like a normal input stream
// but can be initialized from a string
std::istringstream iss(line);
float value;
// The input operator `>>` returns the stream
// And streams can be used as a boolean value
// A stream is "true" as long as everything is okay
while (iss >> value)
{
std::cout << "Value = " << value << '\t';
}
// Flush the standard output stream and print a newline
std::cout << std::endl;
}
}
Given the contents in the file being as in the question, the first three lines of output should be:
Value = 0.5 Value = 0.479425539
Value = 1 Value = 0.841470985
Value = 1.5 Value = 0.997494987
For a 2d-array, I would use a std::vector of std::array:
#include <vector>
#include <array>
...
std::vector<std::array<float, 2>> array;
...
float value1, value2;
if (iss >> value1 >> value2)
{
std::cout << "Values = " << value1 << ", " << value2;
array.emplace_back(std::array<int, 2>{{value1, value2}});
}
Now the first line values are array[0][0] and array[0][1], and the last lines values are array[array.size() - 1][0] and array[array.size() - 1][1].
As C++ has evolved over the years, below is a Modern C++ version.
It uses auto where possible
Uses std::pair to hold 2 values (A std::pair is a specific case of a std::tuple with two elements)
Does not close file (destructor does that at end of block)
Does not read line by line, as the stream uses <space> and <enter> as delimiters
The variables have meaningful names, so the program "reads" easily,
Uses a range for loop to output the data.
Doesn't bring the whole std namespace into the code - Why is “using namespace std” considered bad practice?
.
#include <fstream>
#include <iostream>
#include <vector>
#include <utility>
int main( int argc, char** argv )
{
if ( argc < 1 )
return -1;
const auto fileName = argv[ 1 ];
std::ifstream fileToRead( fileName );
typedef std::pair< double, double > DoublesPair;
std::vector< DoublesPair > rowsOfDoublesPair;
DoublesPair doublePairFromFile;
while ( fileToRead >> doublePairFromFile.first >> doublePairFromFile.second )
{
rowsOfDoublesPair.push_back( doublePairFromFile );
}
for ( const auto row : rowsOfDoublesPair )
std::cout << row.first << " " << row.second << '\n';
}