Taking lists as input till enter is pressed - c++

I am having an integer N.and next N lines contain lists that can have distinct elements from 1-100.But i am not provided length of each list.How to handle this type of input.
If say i have vector > mylist;
I need to populate this list with those lists seperated by just next line.
Say if N=3
1 2 3
4
5 6
Then mylist[0]=[1,2,3] , mylist[1]=[4] , mylist[2]=[5,6].
How to do it in c++?
Mycode : Not correct but i tried.
int main(){
int t;
cin>>t;
cin.ignore();
while(t--){
int n;
cin>>n;
cin.ignore();
lists_t lists;
std::string record;
while ( std::getline( std::cin, record ) &&
record.find_first_not_of( ' ' ) != std::string::npos && lists.size()!=n)
{
std::istringstream is( record );
lists.push_back( std::vector<int>( std::istream_iterator<int>( is ),
std::istream_iterator<int>() ) );
}
for ( const auto &l : lists )
{
for ( int x : l ) std::cout << x << ' ';
std::cout << std::endl;
}
}
}
The problem is that if i enter t=1 and n=3 then instead of following n lines it takes 4 lines and then display the data.Why ?

You can use standard function std::getline ans string stream std::stringstream and of course the container std::list itself.
Here is an example
#include <iostream>
#include <iterator>
#include <list>
#include <sstream>
#include <string>
int main()
{
std::list<std::list<int>> lst;
std::string record;
while ( std::getline( std::cin, record ) &&
record.find_first_not_of( ' ' ) != std::string::npos )
{
std::istringstream is( record );
lst.push_back( std::list<int>( std::istream_iterator<int>( is ),
std::istream_iterator<int>() ) );
}
for ( const auto &l : lst )
{
for ( int x : l ) std::cout << x << ' ';
std::cout << std::endl;
}
return 0;
}
The output is
1 2 3
4
5 6
if the input was the same lines.
If you need to enter a given number of lines then the code could look the following way
#include <iostream>
#include <iterator>
#include <list>
#include <sstream>
#include <string>
int main()
{
std::list<std::list<int>> lst;
std::string record;
size_t n;
std::cin >> n;
std::cin.ignore();
while ( n-- &&
std::getline( std::cin, record ) &&
record.find_first_not_of( ' ' ) != std::string::npos )
{
std::istringstream is( record );
lst.push_back( std::list<int>( std::istream_iterator<int>( is ),
std::istream_iterator<int>() ) );
}
for ( const auto &l : lst )
{
for ( int x : l ) std::cout << x << ' ';
std::cout << std::endl;
}
return 0;
}
The input could look as
3
1 2 3
4
5 6

Related

How to read a integer value from a string in C++? [duplicate]

I realize that this question may have been asked several times in the past, but I am going to continue regardless.
I have a program that is going to get a string of numbers from keyboard input. The numbers will always be in the form "66 33 9" Essentially, every number is separated with a space, and the user input will always contain a different amount of numbers.
I'm aware that using 'sscanf' would work if the amount of numbers in every user-entered string was constant, but this is not the case for me. Also, because I'm new to C++, I'd prefer dealing with 'string' variables rather than arrays of chars.
I assume you want to read an entire line, and parse that as input. So, first grab the line:
std::string input;
std::getline(std::cin, input);
Now put that in a stringstream:
std::stringstream stream(input);
and parse
while(1) {
int n;
stream >> n;
if(!stream)
break;
std::cout << "Found integer: " << n << "\n";
}
Remember to include
#include <string>
#include <sstream>
The C++ String Toolkit Library (Strtk) has the following solution to your problem:
#include <iostream>
#include <string>
#include <deque>
#include <algorithm>
#include <iterator>
#include "strtk.hpp"
int main()
{
std::string s = "1 23 456 7890";
std::deque<int> int_list;
strtk::parse(s," ",int_list);
std::copy(int_list.begin(),
int_list.end(),
std::ostream_iterator<int>(std::cout,"\t"));
return 0;
}
More examples can be found Here
#include <string>
#include <vector>
#include <iterator>
#include <sstream>
#include <iostream>
int main() {
std::string input;
while ( std::getline( std::cin, input ) )
{
std::vector<int> inputs;
std::istringstream in( input );
std::copy( std::istream_iterator<int>( in ), std::istream_iterator<int>(),
std::back_inserter( inputs ) );
// Log process:
std::cout << "Read " << inputs.size() << " integers from string '"
<< input << "'" << std::endl;
std::cout << "\tvalues: ";
std::copy( inputs.begin(), inputs.end(),
std::ostream_iterator<int>( std::cout, " " ) );
std::cout << std::endl;
}
}
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
using namespace std;
int ReadNumbers( const string & s, vector <int> & v ) {
istringstream is( s );
int n;
while( is >> n ) {
v.push_back( n );
}
return v.size();
}
int main() {
string s;
vector <int> v;
getline( cin, s );
ReadNumbers( s, v );
for ( int i = 0; i < v.size(); i++ ) {
cout << "number is " << v[i] << endl;
}
}
// get string
std::string input_str;
std::getline( std::cin, input_str );
// convert to a stream
std::stringstream in( input_str );
// convert to vector of ints
std::vector<int> ints;
copy( std::istream_iterator<int, char>(in), std::istream_iterator<int, char>(), back_inserter( ints ) );
Here is how to split your string into strings along the spaces. Then you can process them one-by-one.
Generic solution for unsigned values (dealing with prefix '-' takes an extra bool):
template<typename InIter, typename OutIter>
void ConvertNumbers(InIter begin, InIter end, OutIter out)
{
typename OutIter::value_type accum = 0;
for(; begin != end; ++begin)
{
typename InIter::value_type c = *begin;
if (c==' ') {
*out++ = accum; accum = 0; break;
} else if (c>='0' && c <='9') {
accum *= 10; accum += c-'0';
}
}
*out++ = accum;
// Dealing with the last number is slightly complicated because it
// could be considered wrong for "1 2 " (produces 1 2 0) but that's similar
// to "1 2" which produces 1 0 2. For either case, determine if that worries
// you. If so: Add an extra bool for state, which is set by the first digit,
// reset by space, and tested before doing *out++=accum.
}
Try strtoken to separate the string first, then you will deal with each string.

Iteration into std::vector<string>

I have a vector of string parameters...
|name1|value1|name2|value2|...
I wanna iterate and cache the name into a string and add it into a vector of names and make the same thing with the value. They are in a std::vector<string>.
I do it:
std::vector<string> names;
std::vector<string> values;
std::vector<string>::iterator pit = p.begin();
while(pit != p.end()){
string name = *pit;
pit++;
string value = *pit;
pit++;
names.push_back(name);
values.push_back(value);
}
But it returns an access violation in vector. It is accessing a bad location returning a <BadPtr>.
How to do this iteration?
Does it have a way of do it using for each?
Check this out:
std::vector<string> names;
std::vector<string> values;
std::vector<string>::iterator pit = p.begin();
while(pit != p.end()){
string name = *pit;
pit++;
if(pit == p.end())
break;
string value = *pit;
pit++;
names.push_back(name);
values.push_back(name);
}
As i said in my comment that problem could be, you didn't put any checking after incrementing pit second time.
Here is a demonstrative program that shows how it can be done using standard algorithm std::partition_copy
#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<std::string> p = { "name1", "value1", "name2", "value2" };
std::vector<std::string> names;
std::vector<std::string> values;
names.reserve( ( p.size() + 1 ) / 2 );
values.reserve( p.size() / 2 );
unsigned int i = 0;
std::partition_copy( p.begin(), p.end(),
std::back_inserter( names ),
std::back_inserter( values ),
[&]( const std::string & ) { return i ^= 1; } );
for ( const auto &s : p ) std::cout << s << ' ';
std::cout << std::endl;
for ( const auto &s : names ) std::cout << s << ' ';
std::cout << std::endl;
for ( const auto &s : values ) std::cout << s << ' ';
std::cout << std::endl;
return 0;
}
The program output is
name1 value1 name2 value2
name1 name2
value1 value2
The same can be done using the range based for statement
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> p = { "name1", "value1", "name2", "value2" };
std::vector<std::string> names;
std::vector<std::string> values;
names.reserve( ( p.size() + 1 ) / 2 );
values.reserve( p.size() / 2 );
unsigned int i = 0;
for ( const std::string &s : p )
{
if ( i ^= 1 ) names.push_back( s );
else values.push_back( s );
}
for ( const auto &s : p ) std::cout << s << ' ';
std::cout << std::endl;
for ( const auto &s : names ) std::cout << s << ' ';
std::cout << std::endl;
for ( const auto &s : values ) std::cout << s << ' ';
std::cout << std::endl;
return 0;
}
Thus your loop can look more simpler like
unsigned int i = 0;
for ( const std::string &s : p )
{
if ( i ^= 1 ) names.push_back( s );
else values.push_back( s );
}
As you see the body of the loop consists only from two statements instead of six or eight statements if to use your approach.

Quickest Way to parse a string of numbers into a vector of ints

I'm wondering what the quickest way to parse a string of numbers into a vector of ints. My situation is that I will have millions of lines of data, formatted like this:
>Header-name
ID1 1 1 12
ID2 3 6 234
.
.
.
>Header-name
ID1 1 1 12
ID2 3 6 234
.
.
.
I would like to discard the "Header-name" field (or maybe use it for sorting later on), and then ignore the ID field and then place the remaining three ints into a vector.
I realize that I could just used boost split and then lexical cast in a couple of for loops with logic to ignore certain data, but I'm not sure if that will give me the quickest solution. I've looked at boost spirit but I don't really understand how to use it. Boost or STL are all ok.
Do you have to use boost?
I've used this function for a while. I believe I got it out of Accelerated C++ and have used it since. Your delimiter seems to be a tab, or multiple white spaces. If you pass the delimiter a " " it might work. I think it will depend on what's actually there though.
std::vector<std::string> split( const std::string& line, const std::string& del )
{
std::vector<std::string> ret;
size_t i = 0;
while ( i != line.size() ) {
while ( ( i != line.size() ) && ( line.substr(i, 1) == del ) ) {
++i;
}
size_t j = i;
while ( ( j != line.size() ) && ( line.substr(j, 1) != del ) ) {
++j;
}
if ( i != j ) {
ret.push_back( line.substr( i, j - i ) );
i = j;
}
}
return ret;
}
You can get each line with this:
int main() {
std::string line;
std::vector<std::string> lines;
while ( std::getline( std::cin, line ) ) {
lines.push_back( line );
}
for ( auto it = lines.begin(); it != lines.end(); it++ ) {
std::vector<string> vec = split( (*it) );
// Do something
}
}
You can get it to return std::vector with a quick modification.
Make each string an int with atoi( myString.c_str() )
Also you'll want to put a check in to skip the headers. Should be trivial.
Note that I've not compiled that above. ;)
On this specific problem, if you want the quickest, I would recommend manual parsing 1 char at a time. Boost Spirit would probably come as a close second and save you lots of ugly code.
Manual parsing one char at a time is key to high speed, as even well optimized converters like atoi and strtol have to deal with many different numeric representations while your example seems to imply that you are only interested in plain unsigned integers. Formatted IOs (scanf, operator<<, etc.) are very slow. Reading lines into intermediate strings will probably have a visible cost.
Your problem is simple enough to parse manually, assuming that the header lines do not contain any '\t' (and assuming that there aren't any IO or format errors):
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
std::vector<unsigned> parse(std::istream &is)
{
bool skipField = true;
char c;
unsigned value = 0;
std::vector<unsigned> result;
while (is.get(c))
{
if (('\t' == c) || ('\n' == c))
{
if (!skipField)
{
result.push_back(value);
}
skipField = ('\n' == c);
value = 0;
}
else if (!skipField)
{
value *= 10;
value += (c - '0');
}
}
return result;
}
int main()
{
const std::string data = ">Header-name\nID1\t1\t1\t12\nID2\t3\t6\t234\n";
std::istringstream is(data);
const std::vector<unsigned> v = parse(is);
for (unsigned u: v)
{
std::cerr << u << std::endl;
}
}
As always, with delightfully underspecified questions like this, there's not a lot more than just showing "a way" to do "a thing". In this case, I used Boost Spirit (because you mentioned it):
Parsing into flat containers
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/adapted.hpp>
#include <map>
std::string const input(
">Header - name1\n"
"ID1 1 1 12\n"
"ID2 3 6 234\n"
">Header - name2\n"
"ID3 3 3 14\n"
"ID4 5 8 345\n"
);
using Header = std::string;
using Container = std::vector<int>;
using Data = std::map<Header, Container>;
int main()
{
namespace qi = boost::spirit::qi;
auto f(input.begin()), l(input.end());
Data data;
bool ok = qi::phrase_parse(f, l,
*(
'>' >> qi::raw[*(qi::char_ - qi::eol)] >> qi::eol
>> *(!qi::char_('>') >> qi::omit[qi::lexeme[+qi::graph]] >> *qi::int_ >> qi::eol)
), qi::blank, data);
if (ok)
{
std::cout << "Parse success\n";
for (auto const& entry : data)
{
std::cout << "Integers read with header '" << entry.first << "':\n";
for (auto i : entry.second)
std::cout << i << " ";
std::cout << "\n";
}
}
else
{
std::cout << "Parse failed\n";
}
if (f != l)
std::cout << "Remaining input: '" << std::string(f, l) << "'\n";
}
Prints
Parse success
Integers read with header 'Header - name1':
1 1 12 3 6 234
Integers read with header 'Header - name2':
3 3 14 5 8 345
Parsing into nested containers
Of course, if you wanted separate vectors for each line (don't expect efficiency) then you can simply replace the typedef:
using Container = std::list<std::vector<int> >; // or any other nested container
// to make printing work without further change:
std::ostream& operator<<(std::ostream& os, std::vector<int> const& v)
{
os << "[";
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(os, " "));
return os << "]";
}
Prints
Parse success
Integers read with header 'Header - name1':
[1 1 12 ] [3 6 234 ]
Integers read with header 'Header - name2':
[3 3 14 ] [5 8 345 ]
You can use something like the following only instead of the string array I used you will get strings from a file
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
int main()
{
std::string s[] = { "ID1 1 1 12", "ID2 3 6 234" };
std::vector<int> v;
for ( const std::string &t : s )
{
std::istringstream is( t );
std::string tmp;
is >> tmp;
v.insert( v.end(), std::istream_iterator<int>( is ),
std::istream_iterator<int>() );
}
for ( int x : v ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
The output is
1 1 12 3 6 234
As for the header then you can check whether tmp is a header and if so you will skip this record.
Here is a simplified version
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iterator>
int main()
{
std::string s[] =
{
"ID1 1 1 12",
">Header-name",
"ID2 3 6 234"
};
std::vector<int> v;
for ( const std::string &t : s )
{
std::istringstream is( t );
std::string tmp;
is >> tmp;
if ( tmp[0] == '>' ) continue;
v.insert( v.end(), std::istream_iterator<int>( is ),
std::istream_iterator<int>() );
}
for ( int x : v ) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
The output will be the same as above.

How would I print numbers from a vector onto a file?

//Here is my code thus far
//HERE I SIMPLY TAKE IN A FILE FULL OF NUMBERS, INCLUDING DECIMAL NUMBERS
ifstream infile;
infile.open("Numbers.txt");
if (!infile) {
cout << "Unable to open the file" << endl;
return;
}
//CREATING VECTORS TO STORE THOSE NUMBERS IN
vector<int> iNumbers;
vector<double> dNumbers;
if (infile) {
int i;
double d;
while (infile >> i && infile >> d) {
iNumbers.push_back(i);
dNumbers.push_back(d);
}
infile.close();
}
/*
NOW ATTEMPTING TO PRINT OR PLACE THOSE NUMBERS INTO TWO DIFFERENT FILES PUTTING THE INTEGERS IN integer.txt AND PUTTING THE DOUBLES IN doubles.txt
*/
ofstream integerOut("integer.txt");
vector<int>::iterator ii;
for (ii = iNumbers.begin(); ii != iNumbers.end(); ++ii)
{
if (ii = int {
}
integerOut << *ii << endl;
cout << *ii << endl;
}
integerOut.close();
ofstream doubleOut("double.txt");
vector<double>::iterator dd;
for (dd = dNumbers.begin(); dd != dNumbers.end(); ++dd)
{
doubleOut << *dd << endl;
cout << *dd << endl;
}
doubleOut.close();
}
//MY CODE ONLY GIVES ME THE FIRST TWO NUMBERS FOR MY integer.txt FILE AND THE LAST DECIMALS FOR MY double.txt. WHAT AM I DOING WRONG?
Further explanation:
I have a file named Numbers.txt with numbers containing
1
5
9.4
3
4
6.3
5
2.2
I am taking the integers and trying to place them into the interger.txt file and I am taking the doubles and placing them into the double.txt file. But in my code I am receiving for integers
1
2
9
3
4
6
5
2
when I want to receive
1
5
3
4
5
only
You can use standard algorithm std::copy. For example
#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>
//...
std::ofstream integerOut( "integer.txt" );
if ( integerOut )
{
std::copy( iNumbers.begin(), iNumbers.end(),
std::ostream_iterator<int>( integerOut, " " ) );
}
std::ofstream doubleOut( "double.txt" );
if ( doubleOut )
{
std::copy( dNumbers.begin(), dNumbers.end(),
std::ostream_iterator<double>( doubleOut, " " ) );
}
Or you can write a code where you will control the output yourself. For example
#include <iostream>
#include <fstream>
//...
std::ofstream integerOut( "integer.txt" );
for ( int x : iNumbers )
{
if ( !( integerOut << x << ' ' ) ) break;
}
std::ofstream doubleOut( "double.txt" );
for ( double x : dNumbers )
{
if ( !( doubleOut << x << ' ' ) ) break;
}
As for the input then as I have understood two integers are followed by one double in the file. So you need to read numbers accordingly.
int i1, i2;
double d;
bool valid = true;
while ( valid )
{
if ( valid = infile >> i1 ) iNumbers.push_back( i1 );
if ( valid && ( valid = infile >> i2 ) ) iNumbers.push_back( i2 );
if ( valid && ( valid = infile >> d ) ) dNumbers.push_back( d );
}
If you do not know whether the next number in the file is integer or double you can distiguish them by the presence of the period in the number. For example
std::string value;
while ( infile >> value )
{
if ( value.find( '.' ) != std::string::npos )
{
double d = std::stod( value );
dNumbers.push_back( d );
}
else
{
int i = std::stoi( value );
iNumbers.push_back( i );
}
}

Convert separate digits into one whole number C++

I need a little more help. I have managed to convert all my chars input from a text file into digits.
Example:
Input from file:
$1,9,56#%34,9
!4.23#$4,983
Output:
1956
349
423
4983
Now, I need to take those individual digits the 1 9 5 6 and make it read as a whole number. The output would look the same but they would actually be whole numbers. Make sense? I have to do this in my outer loop. It also has to be an EOF loop. So, I know I need to take the first digit and multiply it by 10 and add the next digit then multiply all that by 10 until I reach the last number. How can I write that in an efficient non-crashing way?
The input.txt file has the input stated above.
This is what I have so far...
Any help is greatly appreciated
/*
*/
//Character Processing Algorithm
#include <fstream>
#include <iostream>
#include <cctype>
using namespace std;
char const nwln = '\n';
int main ()
{
ifstream data;
ofstream out;
char ch;
char lastch;
int sum;
data.open ("lincoln.txt"); //file for input
if (!data)
{
cout << "Error!!! Failure to Open lincoln.txt" << endl;
system ("pause");
return 1;
}
out.open ("out.txt"); //file for output
if (!out)
{
cout << "Error!!! Failure to Open out.txt" << endl;
system ("pause");
return 1;
}
data.get (ch); // priming read for end-of-file loop
while (data)
{
sum = 0;
while ((ch != nwln) && data)
{
if (isdigit(ch))
out<<ch;
if (ch == '#')
out<<endl;
{
;
}
lastch = ch;
data.get (ch); // update for inner loop
} // inner loop
if (lastch != '#')
out<<endl;
data.get (ch); // update for outer loop
} //outer loop
cout << "The End..." << endl;
data.close (); out.close ();
system ("pause");
return 0;
} //main
If you need simply to output all numbers in the standard stream std::cout (or some other stream as for example file) then you can use the following code as an example. I only substituted the file input for std::cin input in variable line. You can use file input instead of the standard stream.
Also instead of
std::ostream_iterator<char>( std::cout ),
use
std::ostream_iterator<char>( out ),
and instead of
std::cout << std::endl;
use
out << std::endl;
after the std::copy_if call.
Here is the example
#include <iostream>
#include <iterator>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
int main()
{
std::string line;
while ( std::getline( std::cin, line) ) // instead of std::cin use data
{
// std::cout << line << std::endl;
std::string word;
std::istringstream is( line );
while ( std::getline( is, word, '#' ) )
{
// std::cout << word << std::endl;
auto it = std::find_if( word.begin(), word.end(),
[]( char c ) { return ( std::isdigit( c ) ); } );
if ( it != word.end() )
{
std::copy_if( it, word.end(),
std::ostream_iterator<char>( std::cout ),
[]( char c ) { return ( std::isdigit( c ) ); } );
std::cout << std::endl;
}
}
}
}
Test input data is
$1,9,56#%34,9
!4.23#$4,983
The output is
1956
349
423
4983
Or you can define the lambda before its using.
#include <iostream>
#include <iterator>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
int main()
{
std::string line;
while ( std::getline( std::cin, line) ) // instead of std::cin use data
{
// std::cout << line << std::endl;
std::string word;
std::istringstream is( line );
while ( std::getline( is, word, '#' ) )
{
// std::cout << word << std::endl;
auto lm_IsDigit = []( char c ) { return ( std::isdigit( c ) ); };
auto it = std::find_if( word.begin(), word.end(), lm_IsDigit );
if ( it != word.end() )
{
std::copy_if( it, word.end(),
std::ostream_iterator<char>( std::cout ),
lm_IsDigit );
std::cout << std::endl;
}
}
}
}
Read the input file character by character. To check if a character is a digit, use std::isdigit. Then add the number to the back of a string.
If you need to convert a string to an integer, use std::stoi