Get more values with istringstream - c++

When I input [1,0,0,1,0] I get output with 1 0 0 1 0 0, I don't know why there is an extra zero and why the while loop doesn't terminate after ].
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
std::string str;
std::istringstream is;
std::vector<int> numbers;
std::getline(std::cin, str);
is.str(str);
char ch;
is >> ch;
while (!is.eof())
{
int num;
is >> num >> ch;
numbers.push_back(num);
}
for (auto num : numbers)
std::cout << num << " ";
std::cout << std::endl;
return 0;
}

Change the while loop part will get expected behavior:
int num;
while (is >> num >> ch) {
numbers.push_back(num);
}
The eof check is misused here, so the last character read failed and get a default number 0. Read this answer for more details:
https://stackoverflow.com/a/4533102/1292791

Related

Get user input with multple values formated with comma

I want to achive someting like this:
User input values here for example 1,2,3
Your values: 1,2,3 [1,2,3 is inputed by user in one line]
and this values are pushed to array.I need check here if number is not bigger than max number for example 4 and isnt below 1.
I came up with this code. It takes msg to show for user and max num,but as you can see it only can return single value and i have no idea how to modify it to work as i discribed it.
const int getMultipleIntAboveZero(const std::string &msg,int maxNum){
int num;
std::cout<< msg;
while(!(std::cin>>num)|| num < 1 || num > maxNum){
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout<<"\nInvalid input. Try again: ";
}
return num;
}
How can I get integer array inputted by user with commas?
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
std::vector< int > getMultipleIntAboveZero(std::string msg, int maxNum) {
std::istringstream iss (msg);
std::string unit;
std::vector<int> nums;
int num;
while(std::getline(iss, unit, ',')) {
num = std::stoi(unit);
if (num >= 1 && num <= maxNum) {
std::cout << num << '\n';
nums.push_back(num);
} else {
std::cout<<"Invalid input. Try again\n";
}
}
return nums;
}
int main()
{
printf("Your values: ");
std::string msg;
std::cin >> msg;
getMultipleIntAboveZero(msg, 4);
}

I want to take a number from the user and if he type a character or anything else i want him to enter the number again

int x;
if(cin >> x)
cout << "True" << endl;
else
{
cin >> x;
}
It supposes to let me enter the number again but it's end the program without taking the number again
A simple solution is to get the input as string, use regex to check if it's a number and if it is convert it to an int, otherwise ask for input again. Here's an example:
#include <iostream>
#include <string>
#include <regex>
int main() {
std::regex rx(R"((?:^|\s)([+-]?[[:digit:]]+(?:\.[[:digit:]]+)?)(?=$|\s))");
std::string line;
int n;
while ( std::getline(std::cin, line) ) {
if ( std::regex_match(line, rx) ) {
// Input is number
n = std::stoi( line );
std::cout << n << "\n";
break;
}
}
return 0;
}

Iterating through a string with sstream

Here is a piece of code:
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
stringstream ss;
string st = "2,3,55,33,1124,34";
int a;
char ch;
ss.str(st);
while(ss >> a)
{
cout << a << endl;
ss >> ch;
}
return 0;
}
It produces the output:
2
3
55
33
1124
34
But if I remove the line ss >> ch it produces the output: 2.
Why does it stop iterating through the string? And what difference does ss >> ch make?
What difference does ss >> ch make?
ss >> ch takes a character from your stream an store it in your char ch variable.
So here it removes each and every comma (,) from your string.
Why does it stop iterating through the string without ss >> ch?
Without this operation, your iteration stops because ss >> a fails, since it tries to store a comma inside a, an int variable.
Note: If you replace your commas with spaces, you could get rid of ss >> ch, since a space is recognized as a separator.
Example:
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
stringstream ss;
string st = "2 3 55 33 1124 34";
int a;
ss.str(st);
while (ss >> a)
cout << a << endl;
return 0;
}
You can also use this if you like to keep the commas
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
stringstream ss;
string st = "2,3,55,33,1124,34";
std::string token;
ss.str(st);
while(getline(ss, token, ',')) {
cout << token << endl;
}
return 0;
}

C++ - Taking variable number of integers from standard input, n number of times

I'm not able to figure out why the loop in following program is not running exactly testCount times. Please help to make it correct.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
size_t testCount;
cin >> testCount;
if(testCount < 0 || testCount > 100) return 0;
int input;
while(testCount--) {
string instr;
getline(cin,instr);
istringstream iss(instr);
while(iss >> input) {
cout << input << endl;
}
}
return 0;
}
Thanks. I got it. The problem is with getline(). First loop cycle is getting wasted as getline() is taking first line containing just new line character when I pressed enter key after typing testCount value.
std::ws is an input stream manipulator which ignores all whitespaces to the point where the first non-whitespace character is encountered.
Also, getline leaves whitespaces where they are if they don't fit in the line. cin >> ws will discard those.
Here's the bullet proof code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
size_t testCount;
cin >> testCount >> ws;
if(testCount < 0 || testCount > 100) return 0;
int input;
while(testCount--) {
cout << "testCount " << testCount << endl;
string instr;
cin >> ws;
getline(cin,instr);
istringstream iss(instr);
while(iss >> input) {
cout << input << endl;
}
}
return 0;
}

Reading integers from an unorganized text file

#include <iostream>
#include <fstream>
#include <string>
#include <cctype> // isdigit();
using namespace std;
int main()
{
ifstream fin;
fin.open("Sayı.txt");
while (!fin.eof()){
string word;
int n;
fin >> word; //First i read it as a string.
if (isdigit(word[0])){ //checks whether is it an int or not
fin.unget(); //
fin >> n; // if its a int read it as an int
cout << n << endl;
}
}
}
Suppose the text file is something like this:
100200300 Glass
Oven 400500601
My aim is simply to read integers from that text file and show them in console.
So the output should be like
100200300
400500601
You can see my attempt above.As output i get only the last digit of integers.Here's a sample output:
0
1
Simple just try converting the string read to an int using string streams, if it fails then it isn't an integer , otherwise it is an integer.
ifstream fin;
istringstream iss;
fin.open("Say1.txt");
string word;
while (fin>>word )
{
int n=NULL;
iss.str(word);
iss>>n;
if (!iss.fail())
cout<<n<<endl;
iss.clear();
}
I think the following should do what you want (untested code):
int c;
while ((fin >> std::ws, c = fin.peek()) != EOF)
{
if (is_digit(c))
{
int n;
fin >> n;
std::cout << n << std::endl;
}
else
{
std::string s;
fin >> s;
}
}