C++ - Parsing number from std::string [duplicate] - c++

This question already has answers here:
C++ Extract number from the middle of a string
(8 answers)
Closed 5 years ago.
I need to iterate through a shopping list which I have put into a vector and further separate each line by the quantity and item name. How can I get a pair with the number as the first item and the item name as the second?
Example:
vector<string> shopping_list = {"3 Apples", "5 Mandarin Oranges", "24 Eggs", "152 Chickens"}
I'm not sure how big the number will be so I can't use a constant index.
Ideally I would like a vector of pairs.

You can write a function to split quantity and item like following:
#include <sstream>
auto split( const std::string &p ) {
int num;
std::string item;
std::istringstream ss ( p);
ss >>num ; // assuming format is integer followed by space then item
getline(ss, item); // remaining string
return make_pair(num,item) ;
}
Then use std::transform to get vector of pairs :
std::transform( shopping_list.cbegin(),
shopping_list.cend(),
std::back_inserter(items),
split );
See Here

I suggest you the following solution without stringstream just as alternative solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<string> shopping_list = { "3 Apples", "5 Mandarin Oranges", "24 Eggs", "152 Chickens" };
vector< pair<int, string> > pairs_list;
for (string s : shopping_list)
{
int num;
string name;
int space_pos = s.find_first_of(" ");
if (space_pos == std::string::npos)
continue; // format is broken : no spaces
try{
name = s.substr(space_pos + 1);
num = std::stoi(s.substr(0, space_pos));
}
catch (...)
{
continue; // format is broken : any problem
}
pairs_list.push_back(make_pair(num, name));
}
for (auto p : pairs_list)
{
cout << p.first << " : " << p.second << endl;
}
return 0;
}

You can use std::stringstream as follows.
vector< pair<int,string> > myList;
for(int i=0;i<shopping_list.size();i++) {
int num;
string item;
std::stringstream ss;
ss<<shopping_list[i];
ss>>num;
ss>>item;
myList.push_back(make_pair(num,item));
...
}
num is your required number.

Related

stringstream in cpp is continual parsing possible

I've got a vector of strings wherein if the 1st character is "1" then I need to push the integer (represented as a string) into a vector else I just need to print the 1st char.
While using stringstream the following is the code ive written.
vector<string> arr = {"1 23", "2", "1 45", "3", "4"};
vector<int> v;
for(string x : arr){
stringstream ss(x);
string word;
string arr[2];
int i =0 ;
while(ss >> word){
arr[i++] = word;
}
i = 0;
if(arr[0] == "1")
v.push_back(atoi(arr[1]));
else
cout << arr[0] << endl;
Instead of using an array arr, is there a way to take the next word from stringstream once the first word is "1"? Because when I tried the stringstream began all over again from start.
The code uses std::stringstream, but it doesn't take any advantage from this object, like extracting directly an int.
std::vector<std::string> arr = {"1 23", "2", "1 45", "3", "4"};
std::vector<int> v;
for ( auto const& word : arr )
{
std::stringstream ss{ word }; // Initialize with a string,
int first;
if ( ss >> first )
{ // ^^^^^^^^^^^ but extract an int...
if ( first == 1 )
{
int second;
if ( ss >> second ) // and another.
v.push_back(second);
}
else
std::cout << first << '\n';
} // Error handling is left to the reader.
}
Assuming the strings are always well-formed and in the format you describe, and the numbers in the strings are always valid integers, you could so something like this instead:
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
const vector<string> arr = {"1 23", "2", "1 45", "3", "4"};
vector<int> v;
for (const string& s : arr) {
if (s.size() > 2 && s[0] == '1' && s[1] == ' ') {
v.push_back(atoi(s.c_str() + 2));
} else {
cout << s << "\n";
}
}
for (const int i: v) {
cout << i << "\n";
}
}
For strings in the array that don't start with a 1 and a space that you said you're just supposed to print, I just printed out the whole string instead of its first character.
If you're not sure about your strings in the array, you'll need to check for errors first. Also, see How can I convert a std::string to int? for alternatives to atoi().

Problem reading file and storing it in unordered_map

I'm trying to read a file and store it's content into an unordered_map but I've got a little problem. This is my unordered_map:
std::unordered_map<std::string, std::vector<double>> _users;
And this is the content of the file that I'm trying to read:
Mike 4 NA 8 NA NA
Lena NA 8 4 NA 9
I want to store the content in _users in a way that the key is the name, and inside the vectors we have the numbers associated to the name. Moreover I want NA to be equal to 0.
So I managed to do this:
while ( std::getline(file, line))
{
std::istringstream iss(line);
std::string key;
double value;
iss >> key;
dict[key] = std::vector<double>();
while (iss >> value)
{
dict[key].push_back(value);
}
}
But since value is a double, when checking NA it just stops the while loop and I just get, for example with Mike: Mike 4. How can I do in order to get it to read NA and put it as 0 inside the vector ? Thank you for your help!
For your inner loop, you could do:
std::string stringval;
while (iss >> stringval)
{
double value;
try
{
value = std::stod (stringval);
}
catch (...)
{
value = 0.0;
}
dict[key].push_back(value);
}
I also tried something:
#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
int main(int argc, char*[])
{
//1. Read the file and load the map
std::unordered_map<std::string, std::vector<double>> users{};
std::ifstream file{"file.txt"};
std::string line{};
while(std::getline(file, line))
{
std::istringstream iss(line);
std::string key{};
iss >> key;
std::vector<double> values{};
while(iss)
{
double value{0};
if (iss.str() != "NA")
iss >> value;
values.push_back(value);
}
users.insert({key, values});
}
//2. Printing the map
for(auto const &[key, values]: users)
{
std::cout << "Key: " << key << std::endl;
for(auto const value: values)
{
std::cout << value << " ";
}
std::cout << std::endl;
}
return EXIT_SUCCESS;
}

C++ Help: Trying to display each individual integer and running average, read from input file [duplicate]

This question already has answers here:
How do I iterate over the words of a string?
(84 answers)
Closed 6 years ago.
I'm new to C++ so I've been having a bit of trouble getting used to and learning how to deal with it.
So pretty much, what I'm trying to is write a program that would open a textfile containing 5 lines of text, each with 5 integer numbers separated by spaces, then write to the console each individual integer from each line one at a time followed by a comma and the running average. I've managed to get the console to display the whole line of integers and the running average from the first integer of each line. Any help or advice would be appreciated :)
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
string filename;
string mystring;
double average = 0;
double total = 0;
int i = 1;
cout << "Enter name of file to open: " << endl;
cin >> filename;
ifstream inputfile;
inputfile.open(filename.c_str());
if (!inputfile)
{
cout << "Error opening file: " << filename << endl;
return -1;
}
while (!inputfile.eof())
{
getline(inputfile, mystring);
total = atof(mystring.c_str()) + total;
average = total / i;
cout << mystring << " , " << average << endl;
i++;
}
inputfile.close();
}
Just check Split a string in C++? to see how to split mystring into a std::vector<std::string>, then you can iterate through this vector, that will iterate through all items of one line.
Something like that:
void split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss;
ss.str(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
while (!inputfile.eof())
{
getline(inputfile, mystring);
std::vector<std::string> items;
split( mystring, ' ', items );
if ( !items.empty() )
{
for ( std::vector<std::string>::iterator iter = items.begin(); iter != items.end(); ++iter )
{
total = atof(iter->c_str()) + total;
}
// not clear why you were dividing by i
// you may divide by item.size() if you want the average of every items on the line
average = total / items.size();
cout << mystring << " , " << average << endl;
}
}

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++ 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