Can someone help me using fflush in C++
Here is a sample code in C
#include <stdio.h>
using namespace std;
int a,b,i;
char result[20];
int main() {
scanf("%d %d\n", &a, &b);
for (i=1; i<=10; i++) {
printf("5\n");
fflush(stdout);
gets(result);
if (strcmp(result, "congratulation") == 0) break;
}
return 0;
}
This is program for getting interactive input.
I usually use cin and cout so is it possible not using printf and scanf?
The translation to C++ programming style is this:
#include <iostream>
using std::cin;
using std::cout;
using std::string;
int main() {
string line;
int a, b;
if (cin >> a >> b) {
for (int i = 0; i < 10; i++) {
cout << "5" << std::endl; // endl does the flushing
if (std::getline(cin, line)) {
if (line == "congratulations") {
break;
}
}
}
}
return 0;
}
Note that I deliberately added some error checking.
Although I haven't completely understood your question, the C++ version of your program would be something like this (assuming hasil should be result):
#include <iostream>
int main() {
int a,b,i;
std::string result;
std::cin >> a >> b;
for (i=1; i<=10; i++) {
std::cout << "5" << std::endl;
std::cin >> result;
if (result == "congratulation") break;
}
return 0;
}
Note, that std::endl is equivalent to '\n' << std::flush and therefore both puts the line end and calls .flush() on the stream (which is your fflush equivalent).
Actually to get the real equivalent to your scanf call (and not press enter between a and b), you would have to do something like:
#include <sstream>
...
std::string line;
std::cin >> line;
std::istringstream str(line);
str >> a >> b;
If you have need for C IO facilities, include <cstdio>. You now have std::printf and std::fflush etc. You might consider calling std::ios::sync_with_stdio() if you want to use C IO and iostreams interwovenly.
Related
I'm new to C++ coding and just started solving competitive programming problems. I want to solve the following task: https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1620.
I want to find a substring of a string. The problem is that the code below is slow and I fail the submission by getting the "time limit exceeded" "error". What can I do to speed up the code?
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
stringstream ss;
string m;
char prob[100000];
char substring[1000];
int howManyCases = 0;
int numberOfTests = 0;
cin >> numberOfTests;
cin.ignore();
while(numberOfTests--)
{
cin >> prob >> howManyCases;
while(howManyCases--)
{
cin >> substring;
if (strstr(prob,substring)) {
ss << 'y' << "\n";
}
else
{
ss << 'n' << "\n";
}
}
}
m = ss.str();
cout << m;
return 0;
}
i would make you of <algorithm> header:
std::string parent_string = "some string lala";
std::string sub_string = "lala";
auto found = parent_string.find(sub_string);
it will return iterator to where substring is. Then I wou;d use this clause:
if (found != std::string::npos) std::cout << "y\n";
else std::cout << "n\n";
If there is no limitation to the use of standard libraries, It's always a better choice to use it instead of creating your own algorithms (that may not handle some special cases you won't think of ).
Also, swap those huge ugly c-style arrays to std::string.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
cin.ignore();
while(t--){
string s;
getline(cin,s);
int i =0;
int count =0;
while(i<s.size()){
if(s[i]!=' '){
//cout<<count<<":";
s[count++]=s[i];
}
i++;
}
s[count]='\0';
cout<<s<<endl;
}
return 0;
}
Why in the end String is not terminating with '\0'?
For Input:
2
geeks for geeks
g f g
your output is:
geeksforgeeksks
gfgg f g
To remove a character from a string, you should use erase.
See the remove-erase idiom.
std::string is not a C-style null terminated string (but you can obtain one from it). As such, inserting a null character will not terminate it. If you want to truncate a string from the end, you can simply resize() it. Otherwise, if you want to remove characters, you can erase() them.
You say you want to remove spaces. To do that with your existing code, simply replace s[count]='\0'; with s.resize(count);, eg:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin >> t;
cin.ignore();
while (t--){
string s;
getline(cin, s);
int i = 0;
int count = 0;
while (i < s.size()){
if (s[i] != ' '){
//cout<<count<<":";
s[count++] = s[i];
}
i++;
}
s.resize(count);
cout << s << endl;
}
return 0;
}
However, a better way to handle this would look more like this:
#include <iostream>
#include <string>
int main()
{
int t;
std::cin >> t;
std::cin.ignore();
while (t--){
std::string s;
std::getline(cin, s);
std::string::size_type idx = 0;
while ((idx = s.find(‘ ‘, idx)) != std::string::npos){
s.erase(idx, 1);
}
std::cout << s << std::endl;
}
return 0;
}
Alternatively:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
int t;
std::cin >> t;
std::cin.ignore();
while (t--){
std::string s;
std::getline(cin, s);
std::string::iterator iter = std::remove(s.begin(), s.end(), ‘ ‘);
s.erase(iter, s.end());
std::cout << s << std::endl;
}
return 0;
}
After inserting names, and then terminating the input stream pressing CTRL+D (Unix) or CTRL+Z (Win), the program would to prompt another time, to insert ages, but it isn't so. Please, can you tell me why? Thanks.
here, I use the reference for a printing function not present in this code.
compile online https://onlinegdb.com/BkFNcWSgv - there is the same code below: ↓
#include<string>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const vector<string>& read_names(vector<string> &n) {
for(string temp; cin >> temp;)
n.push_back(temp);
return n;
};
const vector<double>& read_ages(vector<double> &a) {
for(double temp; cin >> temp;)
a.push_back(temp);
return a;
};
int main()
{
vector<string> name;
vector<string>& nn = name;
vector<double> age;
vector<double>& aa = age;
nn = read_names(name);
aa = read_ages(age);
return 0;
}
The behavior of Ctrl+D depends on your terminal. I tried it in VSCode and there it seems to close the input stream. I wasn't able to reopen it.
In my Linux terminal (Tilix) Ctrl-D sends EOF. After std::cin.clear() the goodbit is set and I can read user input again. https://en.cppreference.com/w/cpp/io/ios_base/iostate
It behaves different in VSCode and Tilix.
The following code works for me. I don't know the behavior in Windows, Mac or other OS.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
const std::vector<std::string>& read_names(std::vector<std::string>& n) {
for (std::string temp; std::cin >> temp;) n.push_back(temp);
return n;
}
const std::vector<double>& read_ages(std::vector<double>& a) {
for (double temp; std::cin >> temp;) a.push_back(temp);
return a;
}
int main() {
std::vector<std::string> name;
std::vector<std::string>& nn = name;
std::vector<double> age;
std::vector<double>& aa = age;
//std::cout << std::cin.rdstate() << '\n';
nn = read_names(name);
//std::cout << std::cin.rdstate() << '\n';
std::cin.clear();
//std::cout << std::cin.rdstate() << '\n';
aa = read_ages(age);
std::cout << nn.size() << '\n';
std::cout << aa.size() << '\n';
//std::cout << std::cin.rdstate() << '\n';
return 0;
}
#include <iostream>
#include <sstream>
using namespace std;
int get_4()
{
char c = '4';
stringstream s(ios::in);
s << c;
int i;
s >> i;
return i;
}
int main()
{
cout << get_4() << endl;
}
The conversion is not working for me. If I write a character '4' or character array {'4','\0'} to stringstream and then read it out to int i, I don't get back the 4. What is wrong with the above code?
Because you set the stringstream to input-only -- no output.
If you check the fail() bit after trying to extract the int, you'll see it didn't work:
s >> i;
bool b = s.fail();
if( b )
cerr << "WHOA DOGGIE! WE BLOWED UP\n";
In your code, change:
stringstream s(ios::in);
to:
stringstream s;
i am looking for C++ coding for this pascal code
var
jumlah,bil : integer;
begin
jumlah := 0;
while not eof(input) do
begin
readln(bil);
jumlah := jumlah + bil;
end;
writeln(jumlah);
end.
i don't understand using eof on C++
it's purpose is to calculate data from line 1 to the end of the file
edit :
well i tried this but no luck
#include<iostream>
using namespace std;
int main()
{
int k,sum;
char l;
cin >> k;
while (k != NULL)
{
cin >> k;
sum = sum + k;
}
cout << sum<<endl;
}
sorry i am new to C++
You're pretty close, but probably being influenced a bit more by your Pascal background than is ideal. What you probably want is more like:
#include<iostream>
using namespace std; // Bad idea, but I'll leave it for now.
int main()
{
int k,sum = 0; // sum needs to be initialized.
while (cin >> k)
{
sum += k; // `sum = sum + k;`, is legal but quite foreign to C or C++.
}
cout << sum<<endl;
}
Alternatively, C++ can treat a file roughly like a sequential container, and work with it about like it would any other container:
int main() {
int sum = std::accumulate(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
0); // starting value
std::cout << sum << "\n";
return 0;
}
The usual idiom is
while (std :: cin >> var) {
// ...
}
The cin object casts to false after operator>> fails, usually because of EOF: check badbit, eofbit and failbit.
To format what David wrote above:
#include <iostream>
#include <string>
int main()
{
int jumlah = 0;
std::string line;
while ( std::getline(std::cin, line) )
jumlah += atoi(line.c_str());
std::cout << jumlah << std::endl;
return 0;
}
You can also find more information at http://www.cplusplus.com/reference/iostream/