This question already has answers here:
freopen: reverting back to original stream
(2 answers)
How to redirect the output back to the screen after freopen("out.txt", "a", stdout)
(6 answers)
Closed 5 days ago.
#include <iostream>
#include <stdio.h>
#include <fstream>
using namespace std;
int main() {
FILE* fd;
fd = freopen("1.txt", "w", stdin);
int a = 1;
cin >> a;
cout << a;
fclose(fd);
cin >> a;
cout << a;
return 0;
}
I use freopen to connect stdin and 1.txt. Then, i want to close 1.txt and later work with regular stdin, but is isn't works. What i have to do?
(In 1.txt only one number - 1, program at the end puts in console - 11; i want it to put 1, then ask me for a number)
Related
This question already has answers here:
Reading integers from file and store them in array C++ [closed]
(2 answers)
C++ read integers from file and save into array
(2 answers)
Why is “while( !feof(file) )” always wrong?
(5 answers)
Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
(5 answers)
Closed 8 months ago.
So my program is supposed to generate 30 random numbers, put them in a file, then save those numbers in an array, but when I try to print out the numbers in a file they are not the numbers that are in the file but instead are some random huge numbers.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fstream>
using namespace std;
void sortFile() {
fstream f;
int numbers[30];
int n;
f.open("f.txt");
srand(time(NULL));
for(int i; i < 30; i++) {
f << rand() % 30 + (-9) << endl;
}
while(!f.eof()) {
f >> numbers[n];
n++;
}
f.close();
for(int i; i<30;i++) {
cout << numbers[i] << endl;
}
}
int main() {
sortFile();
}
You should close the file after writing, and the open the file again when you start reading. You should also fix the while loop while (!f.eof()) is wrong. And you forgot to initialise n (as pointed out in comments above). Here's some fixed code
f.open("f.txt"); // open file for writing
srand(time(NULL));
for(int i; i < 30; i++) {
f << rand() % 30 + (-9) << endl;
}
f.close();
f.open("f.txt", ios_base::in); // open file for reading
n = 0;
while(f >> numbers[n]) {
n++;
}
f.close();
You have to be careful when switching between reading and writing. In your code you assumed that the file magically rewinds to the beginning when you change from writing to reading, but nothing happens by magic. Closing and reopening the file is one way to rewind the file. Another (perhaps better) way would be to use two separate file variables for reading and writing.
This question already has answers here:
How to read from std::cin until the end of the stream?
(2 answers)
How to break loop by Enter (c++)?
(3 answers)
End of File(EOF) of Standard input stream (stdin)
(6 answers)
Closed 5 years ago.
I was trying to take input variable number of strings and numbers.Found this solution link:
I tried this for numbers:
#include<iostream>
using namespace std;
int main(){
int np;
while (cin>>np){
cout << np<<endl;
}
return 0;
}
for strings:
#include<iostream>
#include<string>
using namespace std;
int main(){
string line;
while (getline(cin, line)){
cout << line <<endl;
}
return 0;
}
But,when I run the code,even if I just press enter it doesn't come out of the loop.The loop should terminate if just an enter key is pressed,but that does not happen.
Please provide suggestions how to achieve this functionality.
You can write
while (std::getline(std::cin, line) && !line.empty()) {
// ...
}
Only keep looping when the fetched string is nonempty.
This question already has answers here:
My code is written twice for uncomprehensible reasons
(6 answers)
Closed 6 years ago.
Every time I run my program, the output in the first line of the do while loop repeats itself. So the output "Enter characters to add..." is output twice at the start of each loop. How do I make it only output once every loop repetition?
main file
#include "LinkedList.h"
#include "ListNode.h"
#include "Node.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
LinkedList<char> *setUpSentence() {
//allocate the linked list objet
LinkedList<char> *sentence = new LinkedList<char>();
char ch;
do {
cout << "Enter characters to add, enter full stop to finish adding." << endl;
ch = cin.get();
sentence->addAtEnd(ch);
} while (ch != '.');
return sentence;
}
int main() {
//call the function, store the returned pointer in sentence variable
LinkedList<char> *sentence = setUpSentence();
while(sentence->size > 0) {
cout << sentence->removeAtFront() << endl;
}
//delete to avoid memory leak
delete sentence;
}
The problem is in here ch = cin.get();. It will automatically read whatever left in the input stream. You need to clean it first with this.
Your program is reading from standard input buffer. Read more about this in
"What is the standard input buffer?"
If you wish to repeat "cout" only once, rewrite it as follows:
char ch;
cout <<"char"<<ch<< "Enter characters to add, enter full stop to finish adding." << endl;
do {
ch = cin.get();
} while (ch != '.');
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 6 years ago.
Its working fine with codeblocks using stdin and stdout, but when i am using freopen to redirect stream or running code in linux with "g++" , the input/output shows erratic behaviour !!! can anyone please tell me what might be the possible issue.
#include<bits/stdc++.h>
using namespace std;
typedef pair<int,string> p;
int main()
{
// freopen("11.txt","r+",stdin);
// freopen("out.txt","w",stdout);
int n,t,i,j,k;
string tmp;
cin>>t;
for(i=1;i<=t;i++)
{
cin>>n;
fflush(stdin);
priority_queue<p,vector<p>,less<p> > s;
for(j=0;j<n;j++)
{ getline(cin,tmp);
map<char,int> mp;
int c=0;
for(k=0;k<tmp.length();k++)
{
if(tmp[k]!=' '){
if(mp.find(tmp[k])==mp.end())
{c++;
mp[tmp[k]]++;
}
}
}
if(!s.empty()&&s.top().first<c)
{ s.pop();}
s.push(make_pair(c,tmp));
}
p ans;
if(!s.empty())
ans =s.top();
string qwe = ans.second;
cout<<"Case #"<<i<<": "<<qwe<<endl;
fflush(stdin);
}
return 0;
}
cin>>n;
followed by
getline(cin,tmp);
doesn't work since the first line usually leave a newline character in the input stream.
Add a line of code to ignore rest of the line from the input stream.
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
right after
cin >> n;
Make sure to add
#include <limits>
to use std::numeric_limits.
I would like my program to read from stdin until EOF, print all input, and repeat. I tried clearing the EOF state of stdin as follows:
#include <string>
#include <iostream>
#include <iterator>
using namespace std;
int main() {
cin >> noskipws;
while (1) {
printf("Begin");
istream_iterator<char> iterator(cin);
istream_iterator<char> end;
string input(iterator, end);
cout << input << endl;
cin.clear();
}
}
After the first input is received and printed, however, the program just infinitely prints "Begin" without waiting for further input.
The approach you're taking there won't work - when 'cin' gives you end-of-file in the context you're using, then cin is closed.
For your stated purpose of "reading text until eof, then doing it again", sorry for missing the nuance of this previously, but if you clone the stdin file descriptor and then use the clone, you can continue reading from these additional file descriptors.
Cloning iostreams isn't easy. See How to construct a c++ fstream from a POSIX file descriptor?
It's a little c-like, but this code will drain one copy of stdin until that stdin closes, then it'll make a new copy and drain that, and on.
#include <iostream>
#include <string>
void getInput(std::string& input)
{
char buffer[4096];
int newIn = dup(STDIN_FILENO);
int result = EAGAIN;
input = "";
do {
buffer[0] = 0;
result = read(newIn, buffer, sizeof(buffer));
if (result > 0)
input += buffer;
} while (result >= sizeof(buffer));
close(newIn);
return input;
}
int main(int argc, const char* argv[])
{
std::string input;
for (;;) {
getInput(input);
if (input.empty())
break;
std::cout << "8x --- start --- x8\n" << input.c_str() << "\n8x --- end --- x8\n\n";
}
}
That is because you have printf("begin"); inside your loop so you are going to get it printed again each time round the loop.
The loop will not wait for input so each time it reads data from stdin - if there is nothing there it immediately gets EOF and so continues looping until some data is present.
Let me know if this doesn't make sense - or if I got it totally wrong.
eg:
#include <string>
#include <iostream>
#include <iterator>
using namespace std;
int main() {
cin >> noskipws;
printf("Begin");
while (1) {
istream_iterator<char> iterator(cin);
istream_iterator<char> end;
string input(iterator, end);
cout << input << endl;
cin.clear();
}
}