Someone will help me, in understanding the while loop in following code about what it does? for example, take input from the user: 1 2 3 8 (input size not given) and one value (any index) show size of an array. it is printing the maximum value of the array. here the answer is 8.
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
int t;
cin >> t;
while(t--)
{
string x;
getline(cin, x);
ll p;
istringstream iss(x);// use of this function
vector<ll> v;
ll ans;
while(iss>>p)// what this loop do
{
v.push_back(p);
}
ll size=v.size()-1;
sort(v.begin(), v.end());
if(size==v[size])
{
ans=v[size-1];
}
else
{
ans=v[size];
}
cout<<ans<<"\n";
}
return 0;
}
istringstream iss(x) creates a string stream called iss consisting of the string x. iss >> p extracts the next element from the iss stream and puts it into p. the return value is int because the variable p is of type int.
while(iss>>p) // get an int value from string stream iss
{
v.push_back(p); // push the int value to the vector
}
you have to use cin.ignore() after cin. otherwise the next getline function will take only new line character. like this:
cin >> t;
cin.ignore();
string str;
cin>>str;
int size = str.size(),arr[size]; //array of size equal to string size
for(int i=0;i<size;i++)
{
arr[i] = (int)str[i]-'0'; //typecasting to int
}
for str[i]-'0' the explanation is :
What is the purpose of using str[i]-'0' where str is a string?
Error may occur if unable to typecast
Using function stoi() (for int values) or stol()(for long values) also optionfor integer values.
int n=56; // use #include<bits/stdc++.h>
string s=to_string(n); // we get string "56" that's for integer to string
int x=stoi(substr(index,length));// for string to integer
Related
I have no idea how to cast str[str.size()-2] and str[str.size()-1] as integers. I need to return answers as integers.
int main()
{
cin>>D;
int k;
int z;
int*tab=new int [D];
for (int i=0;i<D;i++)
{
cin>>tab[i];
}
for (int i=0;i<D;i++)
{
z=silnia(tab[i]);
string str = to_string(z);
if (str.size()>1)
cout<<str[str.size()-2]<<" "<<str[str.size()-1];
else
cout<<"0 "<<str[0];
cout<<endl;
suma=1;
}
return 0;
}
I think you can use substr and atoi.
string std::string::substr (size_t pos = 0, size_t len = npos) const;
Generate substring
Returns a newly constructed string object with its value initialized to a copy of a substring of this object. The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first).
http://www.cplusplus.com/reference/string/string/substr/
int atoi (const char * str);
Convert string to integer
Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.
http://www.cplusplus.com/reference/cstdlib/atoi/
you can include sstream library then simply do the following:
stringstream a(str[str.size()-2]);
int x;
a >> x;
now x has the value of whatever ur string was and you can freely return x
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
//Create a dynamic array to hold the values
vector<int> integers;
//Create a dynamic array to hold the values
vector<double> floating;
int x;
double d;
int sum1=0;
double sum2=0.0;
string line;
ifstream infile;
infile.open("data.txt", ios::in);
while(infile >> x)
{
integers.push_back(x);
}
while(infile >> d)
{
floating.push_back(d);
}
int index = 0;
infile.close();
for(int i=0; i<integers.size(); i++)
{
sum1 += integers[i];
}
for(int i=0; i<floating.size(); i++)
{
sum2 += floating[i];
}
The integer output is working as expected. But the double values are not? Also, the double values start right after the integer values, so I didn't move the file pointer to some other location.
When you do
while(infile >> x)
{
integers.push_back(x);
}
The loop is going to run until the result of infile >> x is false. The result of infile >> x is the state of infile. If infile is good() then it is true, otherwise false. Once that loop gets to a point where infile is no longer good() it stops. Since you haven't done anything to change the state of infile after that, when you get to
while(infile >> d)
{
floating.push_back(d);
}
infile is still bad, so it's false and the loop is skipped.
To reset the state of infile you need to call clear to reset the error state. That would give you
while(infile >> x)
{
integers.push_back(x);
}
infile.clear();
while(infile >> d)
{
floating.push_back(d);
}
This will still have issues though since while(infile >> x) is not going to fail until it reaches the first . in your double values. That means the first double value you read in, and the last integer value will both be incorrect. One way to fix this is to read in the file using a std::string, and then parse the string to figure out if it an integer or floating point value and convert accordingly. Another option is to split up the data and have the integers in one file and the doubles in another.
Read values as a stringand then parse it as a float or an int.
string s;
while(infile >> s)
{
if (s.find('.') != string::npos) { // float
floating.push_back(stof(s));
} else {
integers.push_back(stoi(s));
}
}
If you expect the exponent format of float for e.g. 1e10 to be included, you may want to handle that case as well: (s.find('.') != string::npos) || (s.find('e') != string::npos).
I'm dealing with a competitive programming challenge in which I have to take a line of space-separated integers from standard input, put them into an array, and treat them in a certain way. The problem is that I don't know how many integer I may get in each test case.
In case I know, my code would be like:
int n; // number of integers;
int arr[n];
for(int i = 0; i < n; i++)
cin >> arr[i];
In case I don't have 'n', how would I achieve the same thing?
std::vector<int> is basically a dynamically-sized array of ints. You can keep adding stuff to it and it will grow as necessary. If you are given a number of elements as the first input, you can do something like:
std::vector<int> items;
int count;
std::cin >> count;
// Preallocates room for the items. This is not necessary, it's just an optimization.
items.reserve(count);
while (count > 0) {
int item;
std::cin >> item;
items.push_back(item);
--count;
}
If you are not given the number of items, just read until reading fails:
std::vector<int> items;
int item;
while (std::cin >> item) {
items.push_back(item);
}
Use vectors beacuse vectors are dynamic in size. Keep pushing elements into vector until inputs are there.
std::vector<int> v;
int temp;
while (std::cin >> temp) {
v.push_back(temp);
}
When you will be given the value of n. You can follow any of the following two steps:
Step: 1
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n;
cin >> n; // Input n
vector<int>vv(n); // It will declare a vector(similar to an array) of size n
for(int i = 0; i < n; i++)
{
cin >> vv[i];
}
return 0;
}
Step: 2
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n, number;
cin >> n; // Input n
vector<int>vv; // It will declare an empty vector
for(int i = 0; i < n; i++)
{
cin >> number; // Take a number as input
vv.push_back(number); // Put the input to the last of the vector
}
return 0;
}
When you will not be given the value of n:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int number;
vector<int>vv; // It will declare an empty vector.
while(cin >> number)
{
vv.push_back(number); // Push(put) the input to the back(end/last) of the vector
}
/* In case of reading input from a file,
the loop will continue until the end of the file.
When you'll try it from console, you need to enter
end-of-file command from keyboard.*/
return 0;
}
I was creating a code for rotation of specif number in a string and initially i created it for one user input ! It worked as soon as i added on logic for multiple test case its is showing floating point exception.....
can anyone tell me in the code what caused that error !
#include<iostream>
#include<cstring>
using namespace std;
void stringrot(char str[],int n)
{
int l=strlen(str);
char temp[100];
int k=n%l;
for(int i=0;i<k;i++)
{
temp[i]=str[(l-k+i)];
}
for(int i=0;i<l-k;i++)
{
temp[k+i]=str[i];
}
temp[l]='\0';
cout<<temp;
}
int main()
{
int test;
cin>>test;
while(--test>=0)
{
char str[100];
cin.getline(str,50);
int n;
cin>>n;
stringrot(str,n);
}
}
Here is the code !
Let's take a closer look at the while loop in main
while(--test>=0)
{
char str[100];
cin.getline(str,50);
int n;
cin>>n;
stringrot(str,n);
}
Loop Iteration 1
cin.getline(str,50); << reads a line
cin>>n; << reads an integer. After enter is pressed. Enter
is not an integer. Enter is not read and stays
in the stream
stringrot(str,n);
Loop Iteration 2
cin.getline(str,50); << reads a line. Fortunately there is an enter
still in the stream making it really easy to
find the end of the line. It's the first
character that's going to be read.
cin>>n; << reads an integer. Unfortunately the user
probably thinks they are typing in the string
and doesn't type in a number. Oops.
stringrot(str,n);
Anyway stringrot gets called with stringrot("",0), so the first few lines of stringrot wind up looking like
int l=strlen(""); << l will be zero because the string is emtpy
char temp[100];
int k=n%l; << resolves to 0%0 and an integer divided by zero is BOOM!
Solution:
Change the guts of the while loop to something like
char str[100];
cin.getline(str,50);
int n;
cin>>n;
// discard everything else on the line including the end of line character
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
stringrot(str,n);
Why an integer division results in a floating point error, one that isn't a catchable C++ exception by the way, seems to be mostly historical. More here: Why is this a floating point exception?
Recommendation:
Use std::string not char arrays.
#include<iostream>
#include<cstring>
using namespace std;
//void stringrot(char str[],int n)
void stringrot(string str,int n)
{
//int l=strlen(str);
int l=str.size();
char temp[100];
int k=n%l;
for(int i=0;i<k;i++)
{
temp[i]=str[(l-k+i)];
}
for(int i=0;i<l-k;i++)
{
temp[k+i]=str[i];
}
temp[l]='\0';
cout<<temp;
}
int main()
{
int test;
cin>>test;
while(--test>=0)
{
//char str[100];
//cin.getline(str,50);
string str;
cin>>str;
int n;
cin>>n;
stringrot(str,n);
}
}
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
int n;
cin>>n;
int x=0;
while(n--)
{
char s[3];
cin>>s;
if(strcmp(s,"X++")==0||strcmp(s,"++X")==0)
x+=1;
else
x-=1;
}
cout<<x;
}
The loop worked fine when I removed the strcmp line inside the if statement.
Like πάντα ῥεῖ said, the size of s must be 4 in order to store the '\0' character. Otherwise :
cin >> s; // For example write "X++"
will store your string in s and put '\0' out of the bounds of s.
When the program goes in the loop for the second time, you won't be able to write it because it will get "" (an empty string) every time.
To fix that, just replace 3 with 4 and that will be OK.
Note : If you really want to use C++, I suggest you to use std::string.
#include<iostream>
#include<string>
using namespace std;
int main()
{
int n;
cin >> n;
int x = 0;
while(n--)
{
string s;
cin >> s;
if(s == "X++" || s == "++X")
x+=1;
else
x-=1;
}
cout << x;
return 0;
}