freopen() — Redirect an open file - IBM

Can't figure out how to make freopen() work

I want to use freopen so that I don't manually have to type in the scanf and waste time. I want the scanf to accept the stuff inside the file I am trying to read. I have my code linked below. On line 19 and 27 the freopen file data should be used.
Source link: https://pastebin.com/fLhcqzLP
P.S. I am not sure if I am writing the path correctly. The project folder is personnel_linked_list_database and inside of it is in.txt
Thank you :)
submitted by realism00 to C_Programming [link] [comments]

Why is my line count function breaks my parser?

Here's the simpler Packcc parser that recognizes a simple list of words and can displays line and columns.
The "position" function return the line and colum position of the token. I guess the problem is inside this function.
%auxil "FILE*" # Make the file available in actions. %header{ typedef struct { int line; int column; }Position; Position position(FILE*f, int parsPos); void print_loc(Position p); } list <- line+ {puts("OK");} line <- _ [\n] / _ word _ [\n] word <- [a-z]+ {print_loc(position(auxil, $0s));} _ <- [ \t]* %% int main() { FILE* file = freopen("test.txt", "r", stdin); if(file == NULL) { // try to open. puts("File not found"); } else { // parsing. pcc_context_t *ctx = pcc_create(file); while(pcc_parse(ctx, NULL)); pcc_destroy(ctx); } return 0; } Position position(FILE* f, int parsPos) { Position res = {line: 1, column: 0 }; rewind(f); while (ftell(f) < parsPos) { if (fgetc(f) != '\n') { // Column increases until the end of line.. res.column += 1; } else { // Next line. res.line += 1; res.column = 0; } } return res; } void print_loc(Position p) { printf("%d:%d\n", p.line, p.column); } 
Then I parse this little example.
bla rebla bfkfd 
It always starts by a "Syntax error".
a.out Syntax error 1:0 2:0 4:3 OK make: *** [makefile:4 : all] Erreur 1 
fgetc moves the file cursor but the while condition should replace it like before.
submitted by DriNeo to ProgrammingLanguages [link] [comments]

[C++] Segmentation Fault while using priority queue

i have tried many things none seem to work, tried with array instead of vectorinstead of while tried to use a for loop(in a small range) in case if it stucks in an infinite loop. with and without typecasting while pushing elements in the queue. Just have no clue what went wrong.
#include using namespace std; priority_queueq; priority_queueq2; std::vectorans; void find_ans(priority_queueq1) { long long int a,b,c; while(!q1.empty() && !q2.empty()) { if(q2.empty()) { a = q1.top(); if((long long int)(a/2) > 0) { q2.push((long long int)(a/2)); ans.push_back(a); } q1.pop(); } else if(q1.empty()) { a = q2.top(); if((long long int)(a/2) > 0) { q2.push((long long int)(a/2)); ans.push_back(a); } q2.pop(); } else { b = q1.top(); c = q2.top(); if(b>c) { if((long long int)(b/2) > 0) { ans.push_back(b); q2.push((long long int)(b/2)); } q1.pop(); } else { if((long long int)(c/2) > 0) { ans.push_back(c); q2.push((long long int)(c/2)); } q2.pop(); } } } } int main() { //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); //ios_base::sync_with_stdio(false); //cin.tie(NULL); long long int temp,n,m; cin>>n>>m; for(auto i=0;i>temp; q.push(temp); } find_ans(q); for(long long int i=0;i>temp; cout< 
submitted by mohsinian to learnprogramming [link] [comments]

Stuck on uva 352 https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=288

I have passed all the debug test cases but i still cant get accepted
#include
using namespace std;

int AdjacencyMatrix[25][25];
int solve(int N);
int dfs(int i,int j,int N);


int main()
{
string solution;
char ch;
int counter = 0;
int N, temp, i = 0, j = 0;

// freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);

while(cin >> N)
{
counter++;
getchar();
for(int i =0; i < N; i++)
{
for(int j =0; j < N ; j++)
{
ch = getchar();
AdjacencyMatrix[i][j] = ch - '0';
}
getchar(); //Next Line Character
}
solution += "Image number " + to_string(counter) + " contains " + to_string(solve(N)) + " war eagles.\n";
}
cout << solution;
}

int solve(int N)
{
int sum = 0;
for(int i =0; i < N;i++)
{
for(int j = 0; j < N; j++)
{
if(AdjacencyMatrix[i][j] == 1)
{
sum++;
AdjacencyMatrix[i][j] = 0;
dfs(i,j,N);
}
}
}
return sum;
}

//Performs dfs on node i, j
int dfs(int i,int j,int N)
{
bool goLeft = false, goRight = false, goUp = false, goDown = false;

if(i-1 >= 0)
goUp = true;

if(i+1 < N)
goDown = true;

if(j-1 >= 0)
goLeft = true;

if(j+1 < N)
goRight = true;

if(goUp && (AdjacencyMatrix[i-1][j] == 1))
{
AdjacencyMatrix[i-1][j] = 0;
dfs(i-1,j,N);
}

if( goUp && goLeft && (AdjacencyMatrix[i-1][j-1] == 1))
{
AdjacencyMatrix[i-1][j-1] = 0;
dfs(i-1,j-1,N);
}

if(goUp && goRight &&(AdjacencyMatrix[i-1][j+1] == 1))
{
AdjacencyMatrix[i-1][j+1] = 0;
dfs(i-1,j+1,N);
}

if(goRight && (AdjacencyMatrix[i][j+1] == 1))
{
AdjacencyMatrix[i][j+1] = 0;
dfs(i,j+1,N);
}

if(goLeft && (AdjacencyMatrix[i][j-1] == 1))
{
AdjacencyMatrix[i][j-1] = 0;
dfs(i,j-1,N);
}

if(goDown && (AdjacencyMatrix[i+1][j] == 1))
{
AdjacencyMatrix[i+1][j] = 0;
dfs(i+1,j,N);
}

if(goDown && goRight && (AdjacencyMatrix[i+1][j+1] == 1))
{
AdjacencyMatrix[i+1][j+1] = 0;
dfs(i+1,j+1,N);
}

if(goDown && goLeft && (AdjacencyMatrix[i+1][j-1] == 1))
{
AdjacencyMatrix[i+1][j-1] = 0;
dfs(i+1,j-1,N);
}
}
Please help me debug what is going wrong here . I cant get it
submitted by vectorTree to ProgrammingProblems [link] [comments]

Stuck on uva 352 https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=288

This code passes all the debug test cases and the example test cases provided but still cant get Accepted in the judge please help

#include
using namespace std;

int AdjacencyMatrix[25][25];
int solve(int N);
int dfs(int i,int j,int N);


int main()
{
string solution;
char ch;
int counter = 0;
int N, temp, i = 0, j = 0;

// freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);

while(cin >> N)
{
counter++;
getchar();
for(int i =0; i < N; i++)
{
for(int j =0; j < N ; j++)
{
ch = getchar();
AdjacencyMatrix[i][j] = ch - '0';
}
getchar(); //Next Line Character
}
solution += "Image number " + to_string(counter) + " contains " + to_string(solve(N)) + " war eagles.\n";
}
cout << solution;
}

int solve(int N)
{
int sum = 0;
for(int i =0; i < N;i++)
{
for(int j = 0; j < N; j++)
{
if(AdjacencyMatrix[i][j] == 1)
{
sum++;
AdjacencyMatrix[i][j] = 0;
dfs(i,j,N);
}
}
}
return sum;
}

//Performs dfs on node i, j
int dfs(int i,int j,int N)
{
bool goLeft = false, goRight = false, goUp = false, goDown = false;

if(i-1 >= 0)
goUp = true;

if(i+1 < N)
goDown = true;

if(j-1 >= 0)
goLeft = true;

if(j+1 < N)
goRight = true;

if(goUp && (AdjacencyMatrix[i-1][j] == 1))
{
AdjacencyMatrix[i-1][j] = 0;
dfs(i-1,j,N);
}

if( goUp && goLeft && (AdjacencyMatrix[i-1][j-1] == 1))
{
AdjacencyMatrix[i-1][j-1] = 0;
dfs(i-1,j-1,N);
}

if(goUp && goRight &&(AdjacencyMatrix[i-1][j+1] == 1))
{
AdjacencyMatrix[i-1][j+1] = 0;
dfs(i-1,j+1,N);
}

if(goRight && (AdjacencyMatrix[i][j+1] == 1))
{
AdjacencyMatrix[i][j+1] = 0;
dfs(i,j+1,N);
}

if(goLeft && (AdjacencyMatrix[i][j-1] == 1))
{
AdjacencyMatrix[i][j-1] = 0;
dfs(i,j-1,N);
}

if(goDown && (AdjacencyMatrix[i+1][j] == 1))
{
AdjacencyMatrix[i+1][j] = 0;
dfs(i+1,j,N);
}

if(goDown && goRight && (AdjacencyMatrix[i+1][j+1] == 1))
{
AdjacencyMatrix[i+1][j+1] = 0;
dfs(i+1,j+1,N);
}

if(goDown && goLeft && (AdjacencyMatrix[i+1][j-1] == 1))
{
AdjacencyMatrix[i+1][j-1] = 0;
dfs(i+1,j-1,N);
}
}
submitted by vectorTree to learnprogramming [link] [comments]

Is it possible to restore a daemonized process?

I am daemonizing a program as following. (I'm just posting the bare minimum.)
void detach() { pid_t pid, sid; pid = fork(); if (pid > 0) { exit(0); } sid = setsid(); freopen("in", "rw+", stdin); freopen("out", "w+", stdout); freopen("err", "w+", stderr); } 
This works, now the big question, is there an easy way to reattach stdout and stdin using a c function?
I understand I can use tmux/screen, but I'm looking for a minimal solution. Ideally I'd like to restore the process to an identical twin of the original state.
submitted by MrDum to C_Programming [link] [comments]

How to make this run faster?

so I am just getting into c++, the system that test my tasks says that my simple program to find the greatest divider takes too long. I have no idea how to make a program run faster. please help! here is the code (ignore the first 2 lines) :

include //Greatest Divisor

using namespace std;
int main() { freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); int n, i,d;
cin >> n;
for (i = 1;i < n;i++) { if (n%i == 0); { d = i; }
} cout <
submitted by Ammar2301 to learnprogramming [link] [comments]

Redirecting input/output

For a project we are writing our own shell, like bash. One of the first features I need to implement for this project is the ability to redirect I/O with < > like in bash. The char* args[] is an array of strings for each argument, including the external command (so if the user entered cat filename, args[0] would be cat and args[1] would be filename). Here is the relevant code: ``` int executeExternalCommand(char* args[1026]) {
int pid = fork(); /** Forked processes **/ /* Child process */ if (pid == 0) { /* I/O Redirect */ int stepindex = 0; while (args[stepindex] != NULL) { if (strcmp(args[stepindex], "<") == 0) { freopen(args[stepindex + 1], "r", stdin); } 
// if (args[stepindex] == '<') if (strcmp(args[stepindex], ">") == 0) { int fd = open(args[stepindex + 1], O_CREAT|O_RDWR, 0600); close(1); dup2(fd, 1); } // if(args[stepindex] == '>') stepindex++; }
 execvp(args[0], args); // first parameter is the file descriptor (command), second is args array perror(args[0]); exit(127); /* Parent process */ } else if (pid > 0) { int exitStatus; wait(&exitStatus); if (exitStatus != -1) { return 127; } else { return exitStatus; } } else { perror("Fork failed!"); } return -1; 
} If I run something like `echo "test" > testfile`, then `cat testfile` the contents of testfile are: "test" > testfile `` Which is obviously wrong. It should just betest` Any idea what I'm doing wrong here? The commented out if statements are placeholders since I'll need to parse those differently. Also ignore the freopen line, I've determined that's not going to work and am just focusing on the output redirect for now.
submitted by LorenWard to C_Programming [link] [comments]

Can someone explain the logic of marked lines using "//->"... (*1100 CodeForces problem)

Well, I am not sure how it's used here:
int n,t; vector a; int main() { ios_base::sync_with_stdio(0); //freopen("INPUT.txt", "r", stdin); cin>>t; while(t--) { cin>>n; read(a,n); int pos=0; for(int i=0;i ok1&=(a[(pos+i)%a.size()]==i+1); //-> ok2&=(a[(pos-i+a.size())%a.size()]==i+1); } if(ok1 || ok2) cout<<"YES"< Problem: https://codeforces.com/contest/1203/problem/A
Part of code taken from user: Soul_Full_Of_Thunder

It would be great if someone could explain why Soul_Full_Of_Thunder used that "formula" and is it used anywhere else because I haven't heard of it. Thanks in advance!
submitted by ZenWoR to algorithms [link] [comments]

My code not running in codeblocks but running in online compiler (runtime error may be)

#include
#define IOS ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define pb push_back
#define dg 100009
#define inf 1e18+8
#define mkp make_pair
#define rep(i,n) for(int i=0;i #define repo(i,m,n) for(int i=m;i<=n;i++)
#define ll long long
#define pii pair
#define sc(n) scanf("%d",&n)
#define sc2(m,n) scanf("%d%d",&m,&n);
#define MOD 4294967296
#define fileout freopen("output.txt","w",stdout)
#define filein freopen("input.txt","r",stdin)
#define mem(x,i) memset(x,i,sizeof x)
#define PI acos(-1.0)
#define ff first
#define ss second
#define all(x) x.begin(),x.end()
/*------------------------------Graph Moves----------------------------*/
//const int fx[]= {+1,-1,+0,+0};
//const int fy[]= {+0,+0,+1,-1};
//const int fx[]= {+0,+0,+1,-1,-1,+1,-1,+1}; // Kings Move
//const int fy[]= {-1,+1,+0,+0,+1,+1,-1,-1}; // Kings Move
//const int fx[]={-2, -2, -1, -1, 1, 1, 2, 2}; // Knights Move
//const int fy[]={-1, 1, -2, 2, -2, 2, -1, 1}; // Knights Move
/*---------------------------------------------------------------------*/
using namespace std;
typedef long long i64;
map mp;

int n,k;
multisetmt;
i64 Hash(string &s, int sz)
{
i64 h=0,power=1;
i64 b=347,M=1000000000 + 7;
for(int i=sz-1; i>=0; i--)
{
h= h+ (s[i]*power) %M;
h = h%M;
power= (power*b)%M;
}
return h;
}
void solve(string str, int sz)
{
queueq;
q.push(str);
while(!q.empty() && mt.size() {
string inside=q.front();
q.pop();
int siz=inside.size();
ll rethash=Hash(inside,siz);
if(mp[rethash])continue;
mp[rethash]=1;
mt.insert(sz-siz);
for(int i=0; i {
string nwstringtopush;
for(int j=0; j if(i!=j)nwstringtopush+=inside[j];
q.push(nwstringtopush);
}

}
}
int main()
{
IOS
cinnk;
string mystr;
cin>>mystr;
solve(mystr,n);
int ans=0,cnt =0;
for(auto it= mt.begin(); it!=mt.end() && cnt {
ans += (*it);
}
if(cnt==k)
cout< else
cout<<"-1"<

}
submitted by notan_07 to learnprogramming [link] [comments]

Code review: a simple input scanner for stdio and file

same topic here: Code review: a simple input scanner for stdio and file
I want to learn rust-lang by solving some algorithm problems.
Unfortunately, reading inputs in Rust is not as convenient as in C++ or Python. Especially, I like to read the inputs from file while I am testing or debugging.
For example, in C++: c++ freopen("in.txt", "r", stdin); // comment out this line when submit it, that's all int N; cin >> N; So I wrote the following codes. It works, but it is tedious and not elegant(?) Any suggestions would be appreciated. Thank you and sorry for my poor English.
```rust use std::io::{self, BufRead, BufReader}; use std::fs::File; use std::collections::HashMap;
struct Scan<'a, T: BufRead + 'a> { cur_pos: usize, // position of cur_line cur_line: Option, // current none blank line reader: &'a mut T }
impl<'a, T: BufRead + 'a> Scan<'a, T> { fn new(buf: &'a mut T) -> Self { Scan { cur_pos: 0, cur_line: None, reader: buf } }
fn next_line(&mut self) { let mut line = String::new(); 'outer: loop { self.reader.read_line(&mut line).expect("read error"); for ch in line.chars().next() { if !ch.is_whitespace() { break 'outer; } } } self.cur_pos = 0; self.cur_line = Some(line.trim().to_string()) } fn skip_whitespaces(&mut self) { loop { if self.cur_line.is_none() || self.cur_pos == self.cur_line.as_ref().unwrap().len() { self.next_line(); } if let Some(s) = self.cur_line.as_ref() { // I'm trying to move to the next none whitespace char // this part is tedious, In C++, I can write come code like: // while (this->cur_pos < this->cur_line.size() && iswspace(this->cur_line[this->cur_pos]) { this->cur_pos++; } // but I need to write (let ch = ...) twice here, any suggestions? let ch = s.as_bytes()[self.cur_pos] as char; while self.cur_pos < self.cur_line.as_ref().unwrap().len() && ch.is_whitespace() { self.cur_pos += 1; let ch = s.as_bytes()[self.cur_pos] as char; } if self.cur_pos < self.cur_line.as_ref().unwrap().len() { break; } } } } fn next_char(&mut self) -> char { self.skip_whitespaces(); self.cur_pos += 1; self.cur_line.as_ref().unwrap().as_bytes()[self.cur_pos-1] as char } fn next_string(&mut self) -> String { self.skip_whitespaces(); let mut ret= String::new(); if let Some(s) = self.cur_line.as_ref() { // need improvement here too! // how to put the ch.is_whitespace into while conditions while self.cur_pos < s.len() { let ch = s.as_bytes()[self.cur_pos] as char; self.cur_pos += 1; if ch.is_whitespace() { break; } else { ret.push(ch); } } } ret } fn next_i32(&mut self) -> i32 { let token = self.next_string(); token.parse::().unwrap() } fn next_f64(&mut self) -> f64 { let token = self.next_string(); token.parse::().unwrap() } 
}
fn main() { // this is a solution to https://www.hackerrank.com/challenges/sock-merchant/problem
let input = io::stdin(); // I want to read the inputs from file while I'm debugging // When I submit it, I just need to comment out the next line let input = File::open("in.txt").expect(""); let mut reader = BufReader::new(input); let mut scan = Scan::new(&mut reader); let N = scan.next_i32(); let mut socks = [0; 101]; let mut mps = HashMap::new(); for i in 0..N as usize { socks[i] = scan.next_i32(); *mps.entry(socks[i]).or_insert(0) += 1; } let mut ans = 0; for (k, v) in mps.iter() { ans += v / 2; } println!("{}", ans); 
} ```
submitted by linsinn to rust [link] [comments]

[Computer Science] I am trying to convert from infix to postfix.I got the algorithm but the code not working properly!

#include "stack.hpp" using namespace std; // Operands are all lower case and upper case characters bool isOperand(char c){ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } int precedence(char c) { if(c == '+' || c == '-'){ return 0; } if(c == '*' || c == '/'){ return 1; } if(c == '^'){ return 2; } return -1; } int main(){ freopen("InfixToPostfix.txt", "r", stdin); string input; string output; // output string string solution; int j = 0; int line_counter = 0; while(cin >> solution){ cin >> input; Stack stack; string result; int x = 0; for(int i=0; i= precedence(input[i]) ) { output += stack.peek(); stack.pop(); } } } //store in result the postfix transformation of 'input' result = output; // Checking whether the result you got is correct if(solution == result){ cout << "line " << line_counter << ": OK [" << solution << " " << result << "]" << endl; }else{ cout << "line " << line_counter << ": ERROR [" << solution << " " << result << "]" << endl; } line_counter++; } } 
Here, I was given some made up stack function such as: stack.size(), stack.peek() and stack.push(). They work just like the same as already built-in function for stack.

My InfixToPostfix.txt is
ab+ a+b
abcd^e-fgh*+^*+i- a+b*(c^d-e)^(f+g*h)-i
ab+cd+* (a+b)*(c+d)
The left handside of the file is the correct result.
The right handside is the infix that I need to convert to match the left side.

My algorithm idea is:

My output after complie is:

line 0: ERROR [ab+ ab]
line 1: ERROR [abcd^e-fgh*+^*+i- ababcd^e-fgh*+i]
line 2: ERROR [ab+cd+* ababcd^e-fgh*+iab+cd+]


I think my algorithm is pretty close to be all correct. Might need some adjustments. But the code I'm implementing is probably in the wrong syntax or way here.








submitted by nartuo1997 to HomeworkHelp [link] [comments]

Co

/*

include

using namespace std;
int main(){ freopen("input.txt.txt", "r", stdin); int TestCase, N, i; int Num[1000];
for(TestCase=0; TestCase<10; TestCase++) { for(i=0; i<1000; i++) Num[i] = 0;
cinN; int dem[201]; for (int i =0;i<=200;i++){ dem[i]=0; } for(i=0; i<1000;i++){ cinNum[i]; for (int j =0;j<=200;j++){ if(Num[i] == j){ dem[j]++; break; } } }
int max =0; int t =0; for (int i =0; i<=200;i++){ if (max<=dem[i]){ max=dem[i]; t =i; } }
cout<< "#" << N << " "< }
return 0; } */
//problem 2 /*

include

using namespace std;
int main(){ int m[100][100]; int N;
freopen("input.txt.txt", "r", stdin); for (int tc =0; tc<10;tc++){ int max =0; cin>>N; for (int i =0; i<100;i++){ for (int j =0; j<100;j++){ cin>>m[i][j]; } }
for (int i = 0; i<100;i++){ int tong=0; for (int j = 0; j<100;j++){ tong+=m[i][j]; } if (max<=tong){ max =tong; } }
for (int i = 0; i<100;i++){ int tong =0; for (int j = 0; j<100;j++){ tong+=m[j][i]; } if (max<=tong){ max =tong; } } for (int i =0; i<100;i++){int tong =0; tong += m[i][i];if(max<=tong){max = tong;}} for (int i=0; i<100;i++){int tong =0; tong+=m[i][99-i]; if (max<=tong){max=tong;} }
cout<<"#"< return 0; } */

include

using namespace std;

define M 100

int main(){
freopen("input.txt.txt", "r", stdin); int TC = 10; for (int tc=0;tc>N; for (int i =0; i>m[i][j]; a[i][j] = m[i][j]; } } int min = 10000; for (int i =0;i0 ){ a[x][y] = 0; y= y-1; dem ++; } else if (a[x+1][y] == 1 && x = dem){min =dem; toado = i;} for (int u = 0;u<100;u++){ for (int v =0;v<100;v++){ a[u][v] = m[u][v]; } } } } cout<<"#"< }
submitted by tientuyen07 to u/tientuyen07 [link] [comments]

Given a grid of numbers and a maximum area, what is the largest sum you can get from a rectangle of numbers with that area or less? All numbers are in range [1, 100].

So the solution was the find the possible rectangle dimensions, loop through the possible top-left corners, and use a 2D prefix sum array to keep trying to get the highest possible sum.
Ghetto code:
#include  using namespace std; const int maxWH = 250+2; const int MAXN = 250*250+2; int w, h, n, grid[maxWH][maxWH], pref[maxWH][maxWH], hi, cur; vector > dim; int main() { //freopen("test.txt", "r", stdin); scanf("%d%d%d", &w, &h, &n); for (int i=1; i<=((int)ceil(sqrt(n))); ++i) { dim.push_back({i, n/i}); } for (int i=0; i0) cur -= pref[r-1][c+i.second-1]; if (c>0) cur -= pref[r+i.first-1][c-1]; if (r>0 && c>0) cur += pref[r-1][c-1]; hi = max(hi, cur); } } for (int r=0; r<=h-i.second; ++r) { for (int c=0; c<=w-i.first; ++c) { cur = pref[r+i.second-1][c+i.first-1]; if (r>0) cur -= pref[r-1][c+i.first-1]; if (c>0) cur -= pref[r+i.second-1][c-1]; if (r>0 && c>0) cur += pref[r-1][c-1]; hi = max(hi, cur); } } } printf("%d\n", hi); } 
Problem here
submitted by bobhob314 to programmingchallenges [link] [comments]

How would I compile and run a .cpp file with a text file as input in the same directory?

Recently I started practice using vim for my coding competition training as my friend's suggestion. The main problem is when i put my test case in a text file with the same directory of the .cpp, It compiled but couldn't read the inputs exactly, thus output some random wrong numbers.
I used: freopen("in.txt", "r", stdin);
and compile with g++ s.cpp -o test
then ./test So for competition purpose, I wonder if there are any other ways editing my .vimrc to get an easier way to testing the input file.
submitted by GinRex to vim [link] [comments]

[c++] Opening console in Linux if not present

what I want to do is have my application open a console if it is not open in one something equivalent to this code for Windows
 if(AllocConsole()) { // If no console is present re open standard streams // AllocConsole() returns zero if already present freopen("CONOUT$", "w", stdout); freopen("CONIN$", "r", stdin); } 
I can't seem to find something equivalent for Linux
submitted by lytali to learnprogramming [link] [comments]

Why do I WA? The bobhob314 story

#include  #include  #include  using namespace std; struct coder { int x; int y; int i; }; const int MAXN = 300002; int N; int x, y, bit[MAXN]; long long res[MAXN]; void update(int loc, int val) { while (loc <= MAXN) { bit[loc] += val; loc += loc & -loc; } } long long sum(int loc) { long long ret = 0; while (loc > 0) { ret += bit[loc]; loc -= loc & -loc; } return ret; } bool cmp(const coder &a, const coder &b) { if (a.x < b.x) return true; if (a.x <= b.x && a.y < b.y) return true; return false; } int main() { //freopen("test.txt", "r", stdin); scanf("%d", &N); vector arr (N+1); for (int i=1; i<=N; ++i) { scanf("%d%d", &x, &y); arr[i].x = x; arr[i].y = y; arr[i].i = i; } sort(arr.begin()+1, arr.end(), cmp); for (int i=1; i<=N; ++i) { // printf("%d %d %d\n", arr[i].x, arr[i].y, arr[i].i); update(arr[i].y, 1); res[arr[i].i] = sum(arr[i].y-1); } //printf("-------------------------------\n"); for (int i=1; i<=N; ++i) { printf("%lld\n", res[i]); } } 
submitted by bobhob314 to TSSCC [link] [comments]

question about c++ timeout for CF competition?

I am trying to find the issue in my submission for the following contest. http://codeforces.com/blog/entry/16468 I have followed their advice for number D but am still timing out when the input grows pretty large.
http://codeforces.com/contest/515/submission/21587588
I am 90% sure this is due to my while loop however when I run that exact code in xcode with freopen('absolute filename','r',stdin); I am unable to get any profiling data and gprof suggests that the tuples being made are my bottleneck. I also saw that people are able to solve this in 1 pass rather than loop multiple times. Any ideas? I would like to know where my logic is wrong or if there is some simple optimization that I have missed rather than just viewing the solutions and translating.
copy of code for those who don't want links.
#include  #define print(x){std::cout << x << std::endl;} #define ll long long #define pb push_back #define lop(i,n) for(int i=0;i> q; int main() { ios::sync_with_stdio(false); cin >> n >>m; rep(r,0,n){ rep(c,0,m){ cin >>grid[r][c]; } } bool z = true; while(z == true){ // print("HI"); int ct = 0; z = false; rep(r,0,n){ rep(c,0,m){ if(grid[r][c] == '*'){ ct ++; } if(grid[r][c]=='.'){ int deg = 0; bool up = false; bool left = false; bool right = false; bool down = false; if(c+1=0 and grid[r-1][c] == '.'){ deg ++; up = true; } if(c-1>=0 and grid[r][c-1] == '.'){ deg ++; left = true; } if(deg == 1){ z = true; if(left == true){ q.push(make_tuple(r,c-1,'<')); q.push(make_tuple(r,c,'>')); grid[r][c-1]='@'; } else if(up == true){ q.push(make_tuple(r-1,c,'^')); q.push(make_tuple(r,c,'v')); grid[r-1][c]='@'; } else if(down == true){ q.push(make_tuple(r,c,'^')); q.push(make_tuple(r+1,c,'v')); grid[r+1][c]='@'; } else if(right == true){ q.push(make_tuple(r,c,'<')); q.push(make_tuple(r,c+1,'>')); grid[r][c+1]='@'; } } // printf("%d degs\n",deg); } } } // printf("qsize:%d ct:%d and (n*M):%d\n",q.size(), ct, (n*m)); if(q.size()+ct >= (n*m)){ // print("HIIIIT"); z = true; break; } } // print(q.size()); if(z == false){ cout << "Not unique\n"; return 0; } while(q.empty() == false){ // print("HERE"); // exit(0); int x = get<0>(q.front()); int y = get<1>(q.front()); char s = get<2>(q.front()); // printf("%d %d %c\n",x,y,s); if(grid[x][y] == '.' || grid[x][y] == '@'){ grid[x][y] = s; } q.pop(); } show_grid(grid); return 0; } 
submitted by maximus12793 to cpp_questions [link] [comments]

[C] how to prevent a background process from writing to the terminal

In my OS class, we have an assignment to program a shell with background processing functionality. I believe i have the program putting the process into the background, via the following steps.
  1. setsid() to start new session separate from parent
  2. fork()
  3. umask(0);
  4. chdir();
  5. freopen() for stdin, stdout, and stderr at a new location
as far as various stackoverflow pages have shown, this should be enough, but i'm still getting things printed out to the terminal.
On top of this, we're given the heavy suggestion of signals.
"your shell must execute the command and return immediately, not blocking until the command finishes. The distinction must be made between backgrounding a process that does not need interactive input and one that does, e.g., the who command vs. the vi command. Concepts: Background execution, signals, signal handlers, process groups, asynchronous execution. System calls: sigset(), sigaction() Signals: SIGTTOU"
not sure if i'm missing something or what, but it's getting rather frustrating.
submitted by johnothetree to learnprogramming [link] [comments]

080 Strings Formatando strings com Sprintf freopen() Function - Ring Programming Language - Lesson 132 Linguagem C - YouTube vsCode Setup for Competitive Programming for cpp/c++ in windows 10. Live input output system.

First, attempts to close the file associated with stream, ignoring any errors.Then, if filename is not null, attempts to open the file specified by filename using mode as if by fopen, and associates that file with the file stream pointed to by stream.If filename is a null pointer, then the function attempts to reopen the file that is already associated with stream (it is implementation defined ... The primary use of the freopen() function is to change the file associated with a standard text stream (stderr, stdin, or stdout). Return Value Upon successful completion fopen (), fdopen () and freopen () return a FILE pointer. Here, we are going to learn about the freopen() function of library header stdio.h in C language with its syntax, example. Submitted by Souvik Saha, on January 11, 2019 freopen() function in C. ... //clear the stdin stream buffer //if we don't write this then after taking string fflush ... The freopen() function is typically used to attach the pre-opened streams associated with stdin, stdout, and stderr to other files. Since implementations are not required to support any stream mode changes when the pathname argument is NULL, portable applications cannot rely on the use of freopen () to change the stream mode, and use of this ... Then, independently of whether that stream was successfuly closed or not, freopen opens the file specified by filename and associates it with the stream just as fopen would do using the specified mode. If filename is a null pointer, the function attempts to change the mode of the stream. Although a particular library implementation is allowed ...

[index] [4381] [393] [5505] [7060] [6678] [7478] [68] [6180] [4534] [3031]

080 Strings Formatando strings com Sprintf

freopen() Function - Ring Programming Language - Lesson 132. Skip navigation Sign in. Search É isso ai. Skip navigation Sign in DONATIVOS https://www.paypal.me/jldrpt Lista de donativos http://www.sys4soft.com/home/youtube/ Vídeos postados diariamente no canal. Subscrevam para fic... Programar em C - Funções freopen e fgets / stdin [Parte 2]- Aula 87 by De aluno para aluno. Aula 2. 4:06. Programar em C - Funções fgetc e getc - Aula 88

http://piorosacburgmort.tk