Reputation: 199
Here is a code in which I've been facing difficulties lately-
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,k;
cin >> n >> k;
cin.ignore();
int arr[n];
fill_n(arr , n, 0);
int brr[n];
fill_n(brr , n, 1);
for(int i=1;i<=k;i++){ //Loop 1
char str[8];
cin.getline(str,9);
if(str=="CLOSEALL") //block 1
memset(arr , 0, n * sizeof(arr[0]));
else{
arr[str[6]-'0'-1]=1*brr[str[6]-'0'-1];
if(brr[str[6]-'0'-1]==0)
brr[str[6]-'0'-1]=1;
else
brr[str[6]-'0'-1]=0;
}
int c=0;
for(int j=0;j<n;j++){
if(arr[j]==1)
c++;
}
cout << c << endl;
}
The problem I've been facing is with the input. According to the question, the input commands can be CLICK N
, where N is an integer, or CLOSEALL
(note the exact case and number of whitespaces). Whenever I work with an input of CLICK N
, the program runs fine, but as soon as I input CLOSEALL
, it doesn't execute the block 1(mentioned in the code) and the program terminates immediately, even if Loop 1(mentioned in the code) has to go on till the input value of k
. I assume that it's some problem related to the getline()
buffer, as CLOSEALL
doesn't have any whitespace and is malfunctioning, while CLICK N
has a whitespace and isn't malfunctioning. Can someone suggest how to correct this flush discrepancy, so that the code works perfectly?
PS: I haven't included the question, as I believe it's of no use here. Also, I've included the packages in my code as required. If someone needs the question, I would edit my post.
Upvotes: 0
Views: 111
Reputation: 33
you can try std::stringstream
// swapping ostringstream objects
#include <string> // std::string
#include <iostream> // std::cout
#include <sstream> // std::stringstream
int main () {
std::string str;
std::cin >> str;
std::stringstream ss;
ss << str;
int foo,bar;
ss >> foo >> bar;
std::cout << "foo: " << foo << '\n';
std::cout << "bar: " << bar << '\n';
return 0;
}
// in:
// 100 200
// out:
// foo: 100
// bar: 200
Upvotes: 1