• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Two Words

Member
I just got hired to be a tutor at my university's Computer Science Mentor Center. The center supplies tutoring for C++/Java classes, Computer Architecture, and Discrete Math 1 and 2. I'm pretty excited and a little nervous. Feeling the need to touch base on some material I haven't looked at for a semester or two.

How much of a good impression do you think this job will leave on my resume? Let's say a person applies to an entry-level job with this job being their most significant work/internship experience after college. Does it seem like something significant?
 
I just got hired to be a tutor at my university's Computer Science Mentor Center. The center supplies tutoring for C++/Java classes, Computer Architecture, and Discrete Math 1 and 2. I'm pretty excited and a little nervous. Feeling the need to touch base on some material I haven't looked at for a semester or two.

How much of a good impression do you think this job will leave on my resume? Let's say a person applies to an entry-level job with this job being their most significant work/internship experience after college. Does it seem like something significant?

Honestly, no. But it's more significant than a lot of people have, so maybe yes?

Your best bet for getting an entry level job will come from university job fairs and recruiting events. Firing off resumes blindly is a quick way to lose all hope in humanity.
 
I'm trying to wrap my head around multithreading and I'm stumped.
I want to write a program with one producer and 2 consumers. The consumers should wait for the producer to produce data, and then the producer should wait for the consumers to finish. The consumers don't change the data, and should run in parallel.
This is what I have so far:
Code:
#include <thread>
#include <mutex>
#include <random>
#include <iostream>
#include <chrono>
#include <condition_variable>

std::condition_variable g_produced;
std::condition_variable g_consumed;


void producer(int& data, unsigned int n_consumers)
{
  std::default_random_engine gen;
  std::uniform_int_distribution<int> distr(1,20);

  std::mutex mex;
  std::this_thread::sleep_for(std::chrono::milliseconds(60));
  while (true) {
    {
      std::lock_guard<std::mutex> lk(mex);
      data = distr(gen);
      std::cout << "[producer] produced " << data << std::endl;
    }
    g_produced.notify_all();
    {
      std::unique_lock<std::mutex> lk(mex);
      for (unsigned int i = 0; i < n_consumers; ++i ) {
    	g_consumed.wait(lk);
    	std::cout << "[producer] got notified"  << std::endl;
      }
    }
  }
}


void consumer1(const int& data)
{
  std::mutex mex;
  while (true) {
    {
      std::unique_lock<std::mutex> lk(mex);
      std::cout << "[consumer1] lock, waiting... " << std::endl;
      g_produced.wait(lk);
      std::cout << "[consumer1] data = " << data << std::endl;
    }
    g_consumed.notify_one();
  }
}


void consumer2(const int& data)
{
  std::mutex mex;
  while (true) {
    {
      std::unique_lock<std::mutex> lk(mex);
      std::cout << "[consumer2] lock, waiting... " << std::endl;
      g_produced.wait(lk);
      std::cout << "[consumer2] data = " << data << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(5));
    }
    g_consumed.notify_one();
  }
}


int main()
{
  int data = -1;
  std::thread t1( producer, std::ref(data), 2);
  std::thread t2( consumer1, std::cref(data) );
  std::thread t3( consumer2, std::cref(data) );

  t1.join();
  t2.join();
  t3.join();
}

I have the producer thread sleep for a bit initially to make sure the consumers are waiting, but that's kind of ugly. But anyway, the producer seems to get notified only once and gets stuck in the loop at g_consumed.wait(lk). I can call notify_one() from the producer's wait loop, but then the consumers don't run in parallel. I've tried using a global mutex for everything, but it still gets locked and while it runs the consumers don't run in parallel. Also, from this http://en.cppreference.com/w/cpp/thread/condition_variable/notify_all it sounds like having separate mutex can be better.


Am I approaching this completely the wrong way? I tried finding examples, but most just have one consumer and usually the producer doesn't wait. Also, how can I avoid having that sleep_for at the beginning of the producer?
Is there any good website (or good book) that explains multithreading in C++11 for beginners?

You've got at least one race condition here that I can see. Namely, g_produced.notify_all() will only notify threads that are *already* blocked in a call to g_produced.wait(). What this means is that if your 3 threads fire up and producer produces and calls notify_all() before the other threads have called wait(), then you will get a deadlock.


What you really need here is a semaphore, so that the producer doesn't start producing data until all consumers are ready.

Or better yet, let them consume at their own pace, and allow for the possibility that some of them will miss some data (note this might not always work in practice depending on your requirements)

C++ Concurrency in Action is pretty much the authoritative work on the subject. Very good. It focuses on C++ and C++11 and is more practical in nature.

If you want something both theoretical and practical but which doesn't focus on C++ specifically, try Is Parallel Programming Hard, And, If So, What
Can You Do About It?
Phenomenal book, especially considering that it's completely free.
 

ricki42

Member
You've got at least one race condition here that I can see. Namely, g_produced.notify_all() will only notify threads that are *already* blocked in a call to g_produced.wait(). What this means is that if your 3 threads fire up and producer produces and calls notify_all() before the other threads have called wait(), then you will get a deadlock.


What you really need here is a semaphore, so that the producer doesn't start producing data until all consumers are ready.

Or better yet, let them consume at their own pace, and allow for the possibility that some of them will miss some data (note this might not always work in practice depending on your requirements)

C++ Concurrency in Action is pretty much the authoritative work on the subject. Very good. It focuses on C++ and C++11 and is more practical in nature.

If you want something both theoretical and practical but which doesn't focus on C++ specifically, try Is Parallel Programming Hard, And, If So, What
Can You Do About It?
Phenomenal book, especially considering that it's completely free.

Thanks, I'll look into semaphores and do some reading.
 

Two Words

Member
Honestly, no. But it's more significant than a lot of people have, so maybe yes?

Your best bet for getting an entry level job will come from university job fairs and recruiting events. Firing off resumes blindly is a quick way to lose all hope in humanity.
I see. Well, I hope it is something that can help me get an internship. Also, I'm looking forward to the job doing a better job solidifying my knowledge on the material of these classes. I got As in all of these classes, but I'm sure my knowledge would atrophy if I didn't touch on them often.
 

luoapp

Member
I'm trying to wrap my head around multithreading and I'm stumped.
I want to write a program with one producer and 2 consumers. The consumers should wait for the producer to produce data, and then the producer should wait for the consumers to finish. The consumers don't change the data, and should run in parallel.
This is what I have so far:

Why are all your mutex local? They aren't gonna lock anything.
 
Why are all your mutex local? They aren't gonna lock anything.

Doesn't matter, condition variable mutexes CAN be shared but need not be.

The real way to do this problem is using a semaphore or putting produced numbers in a queue and having each consumer maintain its own state about how much of the queu has been consumed. This way the producer doesn't need to wait for consumption to finish (which is a serialization point)
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
Alright, I'm lost on trying to find why this isn't calculating as I want and I'm tired of banging my head on C while seeing the calculation work in pieces but not the final. I have to be missing something completely obvious here:

(Program start)
Code:
int min;

do
{
printf("Please give number of mins: ";
min = //CommandToGetIntForMin
}
while (min < 1);

//Calculation tiem!
int ounces = 16;
int showerOunces  = 128;
int finalTotal;

//Math tiem!

printf("%i is the final result!\n", finalTotal = (showerOunces * min) / (ounces * min));

Something is failing in the code because min * either of the other two variables before the total will mathmatically be correct and multiply. Even dividing the results of those two together will be mathmatically correct. But I can't seem to get finalTotal to report the correct amount. It just reports "0"? Why? I can't give it the final total/math equation inside the print function? Even if that's the case, I can't assign the total as:

Code:
finalTotal = (showerOunces * min) / (ounces * min);

either. Is it because I have two parenthesis to do first?
 

ricki42

Member
Alright, I'm lost on trying to find why this isn't calculating as I want and I'm tired of banging my head on C while seeing the calculation work in pieces but not the final. I have to be missing something completely obvious here:

Something is failing in the code because min * either of the other two variables before the total will mathmatically be correct and multiply. Even dividing the results of those two together will be mathmatically correct. But I can't seem to get finalTotal to report the correct amount. It just reports "0"? Why? I can't give it the final total/math equation inside the print function? Even if that's the case, I can't assign the total as:

either. Is it because I have two parenthesis to do first?

Your code by itself works for me, the result is 8 as it should be, since the min cancels.
Do you get an error message when you try to assign finalTotal?
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
Your code by itself works for me, the result is 8 as it should be, since the min cancels.
Do you get an error message when you try to assign finalTotal?

Not really. The problem is, I'm using an extreme case (200) as minutes.

And it returns "0" as the product. I'm not sure where the calculation is failing because if (128 * 200) / (200 * 16) = 0, then I've been doing math wrong all this time.
 
Not really. The problem is, I'm using an extreme case (200) as minutes.

And it returns "0" as the product. I'm not sure where the calculation is failing because if (128 * 200) / (200 * 16) = 0, then I've been doing math wrong all this time.

More likely it is your interpretation of the output that is wrong. Because the code should work. Looking at this code, it doesn't appear we're seeing the actual code, because you have stuff like min = //CommandToGetIntForMin, which obviously isn't going to compile.

So we don't have the complete picture. We also don't know what is making you say "it returns 0 as the product". For example, we don't have a copy/paste of your program's output demonstrating that it is printing the message "0 is the final result!".

It would be helpful to see a) the entire source code of the program, and b) a copy/paste of the output exactly as it appears after you run the program, and demonstrating this value of "0" being printed to the screen.
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
It would be helpful to see a) the entire source code of the program, and b) a copy/paste of the output exactly as it appears after you run the program, and demonstrating this value of "0" being printed to the screen.

Well it's for CS50 and they don't like the entire source to be posted around publicly or something like that.

I mean the function for this should be straight forward but I'm not getting the right answer to be assigned. Which is making me "WTF" because from what I see my code is correct.

But uh... I'll PM you two a gist of it.
 
Well it's for CS50 and they don't like the entire source to be posted around publicly or something like that.

I mean the function for this should be straight forward but I'm not getting the right answer to be assigned. Which is making me "WTF" because from what I see my code is correct.

But uh... I'll PM you two a gist of it.

You should either try using a debugger to inspect your program at runtime, or add some more print statements.

For example:

Code:
int min;

do
{
printf("Please give number of mins: ";
min = //CommandToGetIntForMin
}
while (min < 1);

printf("min = %d\n", min);

//Calculation tiem!
int ounces = 16;
int showerOunces  = 128;
int finalTotal;

//Math tiem!

printf("showerOunces * min = %d\n", showerOunces * min);
printf("ounces * min = %d\n", ounces * min);

printf("%i is the final result!\n", finalTotal = (showerOunces * min) / (ounces * min));
printf("finalTotal = %d\n", finalTotal);

and paste the output of the program when you run it
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
Well, that's what I've been doing in regards to the last printf action (breaking the math equation apart and then having it return the stuff that isn't commented out). I'm trying to calculate the math through that as an argument that is assigned to the value that it's going to return (total) but I think I might be misunderstanding the printf arguments and it can't really do an assignment AND return that assignment.

Edit: I am stupid. I've been thinking about the equation wrong. Since they're both the same unit of measurement, I just convert the time with one of them that I need and then divide by the base amount that I needed. *slaps forehead* The math was already correct and just giving me a redundant answer because of the wrong equation.
 

Aikidoka

Member
I got a question about using scp for getting files off of remote hosts.
At my work, I use a local supercomputer. This requires me to first ssh to usrname@login, enter a password, and then ssh into usrname@localcluster by entering another password.
I cannot ssh into usrname@localcluster from my machine. So to get files from that remote machine, I ssh into login, scp from the remote machine to the login, log out and then scp the file from login to my machine.

My question is if there is a faster way for me to do this? It's a bit of a pain.
 

luoapp

Member
I got a question about using scp for getting files off of remote hosts.
At my work, I use a local supercomputer. This requires me to first ssh to usrname@login, enter a password, and then ssh into usrname@localcluster by entering another password.
I cannot ssh into usrname@localcluster from my machine. So to get files from that remote machine, I ssh into login, scp from the remote machine to the login, log out and then scp the file from login to my machine.

My question is if there is a faster way for me to do this? It's a bit of a pain.
Can you scp from localcluster to your pc? Or ssh tunnel?
 

Massa

Member
I got a question about using scp for getting files off of remote hosts.
At my work, I use a local supercomputer. This requires me to first ssh to usrname@login, enter a password, and then ssh into usrname@localcluster by entering another password.
I cannot ssh into usrname@localcluster from my machine. So to get files from that remote machine, I ssh into login, scp from the remote machine to the login, log out and then scp the file from login to my machine.

My question is if there is a faster way for me to do this? It's a bit of a pain.

You can generate ssh keys to automate that stuff.
 

Aikidoka

Member
Can you scp from localcluster to your pc? Or ssh tunnel?

I tried to scp from the local cluster using my IP address given by ifconfig, but ssh said Connection refused.

Based on just reading up about ssh tunneling, I don't think it's something I should do.

You can generate ssh keys to automate that stuff.

What do you mean? Does it matter if the codes I have to enter to login change frequently?
 

Massa

Member
I tried to scp from the local cluster using my IP address given by ifconfig, but ssh said Connection refused.

Based on just reading up about ssh tunneling, I don't think it's something I should do.



What do you mean? Does it matter if the codes I have to enter to login change frequently?

I'm on my phone right now but if you Google 'SSH automatic login keys' you should easily find some tutorials. The idea is to unlock your remote hosts with the login on your home PC.
 

ssharm02

Banned
Java question, I have 6 shape classes and i want to create a object array in the main. I have one interface class called Shapes3D

how would i create this object array?

Shapes3d [] s = new Shapes3D[input int from user]
s[1] = new Cylinder();

etc etc

is this the way to do it?
 

Somnid

Member
Java question, I have 6 shape classes and i want to create a object array in the main. I have one interface class called Shapes3D

how would i create this object array?

Shapes3d [] s = new Shapes3D[input int from user]
s[1] = new Cylinder();

etc etc

is this the way to do it?

Close but you have to cast each shape as a Shapes3D to put it into the array.
 

upandaway

Member
Java question, I have 6 shape classes and i want to create a object array in the main. I have one interface class called Shapes3D

how would i create this object array?

Shapes3d [] s = new Shapes3D[input int from user]
s[1] = new Cylinder();

etc etc

is this the way to do it?
Yeah but just to make sure you're losing the ability to differentiate between the different shapes, if you access them through the array you will not be able to do class-specific things with them.

It's useful if you only care about them being able to handle the same behavior in different ways
 

Koren

Member
Yeah but just to make sure you're losing the ability to differentiate between the different shapes, if you access them through the array you will not be able to do class-specific things with them.

It's useful if you only care about them being able to handle the same behavior in different ways
I'd say it's useful to have at least a virtual method that give information about the original type, so that you can cast them back into their specific classes when you need to handle differently each kind of object.

40 years late to the party
And counting. Clang and MSVC are nice to offer this, but I'd far prefer seeing modules in a proper C++ specification.

Is there any good website (or good book) that explains multithreading in C++11 for beginners?
And forward the suggestion to software engineers from french telecom R&D... they could find it some use ;)
 
And counting. Clang and MSVC are nice to offer this, but I'd far prefer seeing modules in a proper C++ specification.

So would the developers of clang and msvc ;-) turns out it's pretty difficult to do it in a way that makes everyone happy. Modules are the #1 topic of discussion at every standards committee meeting, the reason they're releasing their implementations now is because they know how long standardization takes, not because they're not planning to standardize

The existing proposal is already out there for anyone to read. N4465 although there will inevitably be some changes before this is finalized
 

Koren

Member
I know... It's just that I'm reluctant to use something tied to a compiler, that'll probably become deprecated sooner or later.

I'd prefer they settle quicker. Both solutions seem usable, at first glance, and as you say, they won't please everyone...
 

JeTmAn81

Member
I'm trying to wrap my head around multithreading and I'm stumped.
I want to write a program with one producer and 2 consumers. The consumers should wait for the producer to produce data, and then the producer should wait for the consumers to finish. The consumers don't change the data, and should run in parallel.
This is what I have so far:
Code:
#include <thread>
#include <mutex>
#include <random>
#include <iostream>
#include <chrono>
#include <condition_variable>

std::condition_variable g_produced;
std::condition_variable g_consumed;


void producer(int& data, unsigned int n_consumers)
{
  std::default_random_engine gen;
  std::uniform_int_distribution<int> distr(1,20);

  std::mutex mex;
  std::this_thread::sleep_for(std::chrono::milliseconds(60));
  while (true) {
    {
      std::lock_guard<std::mutex> lk(mex);
      data = distr(gen);
      std::cout << "[producer] produced " << data << std::endl;
    }
    g_produced.notify_all();
    {
      std::unique_lock<std::mutex> lk(mex);
      for (unsigned int i = 0; i < n_consumers; ++i ) {
    	g_consumed.wait(lk);
    	std::cout << "[producer] got notified"  << std::endl;
      }
    }
  }
}


void consumer1(const int& data)
{
  std::mutex mex;
  while (true) {
    {
      std::unique_lock<std::mutex> lk(mex);
      std::cout << "[consumer1] lock, waiting... " << std::endl;
      g_produced.wait(lk);
      std::cout << "[consumer1] data = " << data << std::endl;
    }
    g_consumed.notify_one();
  }
}


void consumer2(const int& data)
{
  std::mutex mex;
  while (true) {
    {
      std::unique_lock<std::mutex> lk(mex);
      std::cout << "[consumer2] lock, waiting... " << std::endl;
      g_produced.wait(lk);
      std::cout << "[consumer2] data = " << data << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(5));
    }
    g_consumed.notify_one();
  }
}


int main()
{
  int data = -1;
  std::thread t1( producer, std::ref(data), 2);
  std::thread t2( consumer1, std::cref(data) );
  std::thread t3( consumer2, std::cref(data) );

  t1.join();
  t2.join();
  t3.join();
}

I have the producer thread sleep for a bit initially to make sure the consumers are waiting, but that's kind of ugly. But anyway, the producer seems to get notified only once and gets stuck in the loop at g_consumed.wait(lk). I can call notify_one() from the producer's wait loop, but then the consumers don't run in parallel. I've tried using a global mutex for everything, but it still gets locked and while it runs the consumers don't run in parallel. Also, from this http://en.cppreference.com/w/cpp/thread/condition_variable/notify_all it sounds like having separate mutex can be better.


Am I approaching this completely the wrong way? I tried finding examples, but most just have one consumer and usually the producer doesn't wait. Also, how can I avoid having that sleep_for at the beginning of the producer?
Is there any good website (or good book) that explains multithreading in C++11 for beginners?

Dunno if it will be useful since this example has only one consumer and yours has two, but this video from UC Berkeley goes over a similar situation:

https://youtu.be/bQT3OpcJJ64?list=PL3A5075EC94726781&t=3988

It's from an operating systems class. I've been listening to these lectures off and on for the past few months. I'm getting some good info on these topics but haven't actually written any code so it's mostly surface stuff for me.
 

ricki42

Member
Dunno if it will be useful since this example has only one consumer and yours has two, but this video from UC Berkeley goes over a similar situation:

https://youtu.be/bQT3OpcJJ64?list=PL3A5075EC94726781&t=3988

It's from an operating systems class. I've been listening to these lectures off and on for the past few months. I'm getting some good info on these topics but haven't actually written any code so it's mostly surface stuff for me.

Thanks. Watching right now.
 

Two Words

Member
How can I make this loop read and print input from the keyboard until the user simply hits return without having the newline character being captured in my array? This is in C.

Code:
do
{
	fgets(input, 127, stdin);
	printf("%s", input);
}while (input[0]!= '\n');
 
How can I make this loop read and print input from the keyboard until the user simply hits return without having the newline character being captured in my array? This is in C.

Code:
do
{
	fgets(input, 127, stdin);
	printf("%s", input);
}while (input[0]!= '\n');

Code:
std::string str;
std::cin >> str;

Edit: Oops, if you really must use C:

Code:
char input[127];
for (char *next = input; next != input+127; ++next) {
    char c = fgetc(stdin);
    if (c = '\n') break;
   *next = c;
}

Or

Code:
fgets(input, 127, stdin);
int len = strlen(input);
if (input[len-1] == '\n')
    input[len-1] = 0;
 

Ambitious

Member
The heading for the area on the resume is "Languages and Technologies" and every section I have is a bullet point under it. Final bullet point is for technologies instead

Template is what I used and I filled it in with random stuff.

Cheers. Another question: How do you define "Some" and "Limited" experience? What's your criteria?

I'm not quite sure where to put some languages. A specific example: Python. So far, I've only written small, single-file scripts. I've never worked on bigger Python projects. And as I've got a bad memory, I tend to forget syntactic details after not working with a language for a while (e.g. the specific style of a foreach loop). So if I had to write a Python program using pen and paper during an interview, I'd screw up. I need Google and the API documentation. Yet, I feel somewhat comfortable using the language.

Nevertheless, as I haven't worked on anything substantial, I think that's rather one for the Limited section, isn't it?

It's a similar situation with bash scripts. I've written many small to medium sized scripts, but for the love of god, I can't remember anything. What's the difference between [[ exp ]] and [ exp ] again? Don't I need a semicolon after that expression? Was $? the number of arguments or was it $#? Is it "find <path> <conditions>" or "find <conditions> <path>"? If I want to split up a string using some separator, which tool do I use again?
I just can't remember any of these. Every single time I work on a script, I spend more time searching Stack Overflow for details like these. Still, I think I'd include it with "Some Experience".

Another example: C++. Back in highschool, we learned C for two years. Then we dabbled in C++ for one semester before moving on to Java. I haven't used it ever since. Even if I tried to refresh my memory, I don't think I'd be able to produce anything usable. I would not include it in my resume at all.
 
Anyone experienced in R and Rstudio? My brother is doing a thing and is having issues with windows' file system. He's...the kind of guy that doesn't like windows very much to begin with :/
 

theecakee

Member
I'm getting my ass kicked in Algorithms...may be the first course I have to withdraw with a W from and take another semester. This coursera course will pretty much be what we're covering: https://www.coursera.org/course/aofa

Understanding what the algorithms do is the easy part, but when they throw in time complexity analysis stuff from Discrete Math and Calculus...everything goes horribly wrong.

Any advice or resources?
 
I'm getting my ass kicked in Algorithms...may be the first course I have to withdraw with a W from and take another semester. This coursera course will pretty much be what we're covering: https://www.coursera.org/course/aofa

Understanding what the algorithms do is the easy part, but when they throw in time complexity analysis stuff from Discrete Math and Calculus...everything goes horribly wrong.

Any advice or resources?

you might have answered your own question there... are you sure your basics are strong enough?
 

upandaway

Member
I'm getting my ass kicked in Algorithms...may be the first course I have to withdraw with a W from and take another semester. This coursera course will pretty much be what we're covering: https://www.coursera.org/course/aofa

Understanding what the algorithms do is the easy part, but when they throw in time complexity analysis stuff from Discrete Math and Calculus...everything goes horribly wrong.

Any advice or resources?
We had a lot of trouble with it this semester too but I managed to ace the test in the end. It's really hard but super satisfying too.

Judging from that coursera though your material seems to be different from what mine was (well, it's a 6 week course) so I don't know how much I can offer. My advice is to solve all the homework by yourself. Understanding solutions won't really do anything (hints are great though). Our assignments were super intense and they're the only reason I didn't get lost, but we were practically putting 2-3 full days a week on the homework alone.

I wouldn't say calculus was important to us but you have to be a master of everything discrete math.

If you have any specific questions we can try to help, I like the subject
 

Two Words

Member
I'm having some trouble with this C project that uses command line arguments. Here's the set of commands it should take. Let's assume the program is called program

Code:
./program
If it takes no arguments, it should simply read from the keyboard and print to the terminal.

Code:
./program file1.txt file2.txt file 3.txt filen.txt
If it takes n text-based files as arguments, it should print each file to the console.

./program -f output.txt
If it has the f option, it should read input from the keyboard and output to the given file argument.

Code:
./program -f output.txt file1.txt file2.txt file3.txt filen.txt
If it has the f option and multiple text-based file arguments, it should put the data from each of those file1.txt - filen.txt into output.txt in order from left to right.


I've done each of these and they work, but my professor says that:
"You must use freopen(...) to create the stream for the program&#8217;s output if the output is going to standard output."


This is what I am having trouble with. I don't really understand how to use freopen() and everything I'm reading about it isn't helping me a whole lot. The way I made my program, I just handled each case as a separate function and properly made my main() function figure out which case I'm dealing with. And I don't need to really use freopen() to get the job done.
 

luoapp

Member
This is what I am having trouble with. I don't really understand how to use freopen() and everything I'm reading about it isn't helping me a whole lot. The way I made my program, I just handled each case as a separate function and properly made my main() function figure out which case I'm dealing with. And I don't need to really use freopen() to get the job done.

He just wants to see this
Code:
#include <stdio.h>

int main ()
{
  freopen ("myfile.txt","w",stdout);
  printf ("This sentence is redirected to a file.");
  fclose (stdout);
  return 0;
}
 

Two Words

Member
He just wants to see this
Code:
#include <stdio.h>

int main ()
{
  freopen ("myfile.txt","w",stdout);
  printf ("This sentence is redirected to a file.");
  fclose (stdout);
  return 0;
}

From my understanding, I would see the string in that printf() statement in a file called my file.txt, correct? But the line I quoted above makes it seem like it should be redirected to stdout, right?
 

vypek

Member
Cheers. Another question: How do you define "Some" and "Limited" experience? What's your criteria?

I'm not quite sure where to put some languages. A specific example: Python. So far, I've only written small, single-file scripts. I've never worked on bigger Python projects. And as I've got a bad memory, I tend to forget syntactic details after not working with a language for a while (e.g. the specific style of a foreach loop). So if I had to write a Python program using pen and paper during an interview, I'd screw up. I need Google and the API documentation. Yet, I feel somewhat comfortable using the language.

Nevertheless, as I haven't worked on anything substantial, I think that's rather one for the Limited section, isn't it?

It's a similar situation with bash scripts. I've written many small to medium sized scripts, but for the love of god, I can't remember anything. What's the difference between [[ exp ]] and [ exp ] again? Don't I need a semicolon after that expression? Was $? the number of arguments or was it $#? Is it "find <path> <conditions>" or "find <conditions> <path>"? If I want to split up a string using some separator, which tool do I use again?
I just can't remember any of these. Every single time I work on a script, I spend more time searching Stack Overflow for details like these. Still, I think I'd include it with "Some Experience".

Another example: C++. Back in highschool, we learned C for two years. Then we dabbled in C++ for one semester before moving on to Java. I haven't used it ever since. Even if I tried to refresh my memory, I don't think I'd be able to produce anything usable. I would not include it in my resume at all.

Some experience is what I'd call something I worked with for at least a few semesters for a few years and limited is something I barely used (probably just for one class). I might be able to tell you things about the language but I'm not ready to do any serious development with it. I'd say just base it on how comfortable you feel using the language. The top language on my resume was Java because I've used that the most. Even though it was for small projects I know it the best of the languages I have used.
 

luoapp

Member
From my understanding, I would see the string in that printf() statement in a file called my file.txt, correct? But the line I quoted above makes it seem like it should be redirected to stdout, right?

This :
freopen ("myfile.txt","w",stdout);

will redirect stdout to myfile.txt
 
From my understanding, I would see the string in that printf() statement in a file called my file.txt, correct? But the line I quoted above makes it seem like it should be redirected to stdout, right?

freopen takes a file stream, closes it (if it's open) and opens a new file to associate the stream with. So you take a file stream: stdout, and say: "this file stream should now point to file.txt instead". Perhaps the trouble you're having understanding is that stdout is, in fact, a file stream no different from any other. It's just that by default it's pointing to a text terminal. But where the output goes doesn't really matter to us as programmers.

There are different ways to solve this task:
1. Your code always outputs info to the same file stream, but you change what that file stream means. This is what your teacher wants.

2. You put your code in a function that takes a file stream as an argument and you output to that.

3. You copy paste your code and have slightly different version of it depending on where it's supposed to write to. This is bad coding. What if you need to change something? Now you need to change the code at several places. This is a mess to maintain.
 

gaugebozo

Member
Anyone experienced in R and Rstudio? My brother is doing a thing and is having issues with windows' file system. He's...the kind of guy that doesn't like windows very much to begin with :/

I work with R and Rstudio, although most of my experience is with Ubuntu Linux. What's your problem?
 

Two Words

Member
Edit, never mind I got it working.


freopen takes a file stream, closes it (if it's open) and opens a new file to associate the stream with. So you take a file stream: stdout, and say: "this file stream should now point to file.txt instead". Perhaps the trouble you're having understanding is that stdout is, in fact, a file stream no different from any other. It's just that by default it's pointing to a text terminal. But where the output goes doesn't really matter to us as programmers.

There are different ways to solve this task:
1. Your code always outputs info to the same file stream, but you change what that file stream means. This is what your teacher wants.

2. You put your code in a function that takes a file stream as an argument and you output to that.

3. You copy paste your code and have slightly different version of it depending on where it's supposed to write to. This is bad coding. What if you need to change something? Now you need to change the code at several places. This is a mess to maintain.

I think I did a better job now with this now. Thanks.
 
Next week I'll have to pass the OCA Java SE 7 Programmer 1 certification. I have some mock exams to do but it seems so fucking hard... I mean I know how to code in Java (SE & EE) but there are some weird ass questions >< Plus, the whole thing is in english only, so some questions are a bit hard to understand for me :/
Got 58% on my first mock and 62% on my second but I can't help but think I got lucky on some answers...

Any tips or good website to study ? :p
 
Top Bottom