Jump to content
  • Advertisement
Sign in to follow this  
fishfin

C++ help

This topic is 4348 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement

std::string filename;
std::cout << "Enter the file name:" << std::endl;
std::getline(std::cin,filename);

if (!std::cin) return;

std::ifstream input(filename.c_str());

Share this post


Link to post
Share on other sites
Quote:
Original post by fishfin
why is there "std::" in front of "cout" is that nesisary for the code to work?


cout is in the namespace std. You can also use cout without the namespace qualifier by writing:

using std::cout;

Avoid the oft-cited but dangerous using namespace std;, which will pollute your global namespace.

Share this post


Link to post
Share on other sites
In modern C++, all symbols in the Standard C++ Library are placed within the std namespace. This helps minimize name collisions with your own symbols (the SC++L provides a find algorithm, for instance; without a namespace, you'd have to mangle your own function name for something so common).

Share this post


Link to post
Share on other sites
I got a compiler eror on this line:

if (!std::cin) return;


saying:

return-statement with no value, in function return 'int'

Share this post


Link to post
Share on other sites
Quote:
Original post by fishfin
I got a compiler eror on this line:

if (!std::cin) return;


saying:

return-statement with no value, in function return 'int'


This code was meant as an example of usage, not code to be copy-pasted. Understand how it works, and rewrite it so it fits in your own program.

Share this post


Link to post
Share on other sites
#include <iostream>
#include <fstream>
#include <string>

int main()
{
std::string filename, text;

std::cout<<"What is the filename:";
std::getline(std::cin,filename);

std::ofstream file1 (filename.c_str());
std::cin>>text;

std::cout<< text;
}

I tried this and when I ran it nothing happened after I entered the filename, I had already created a file with that name and put some text in it...

Share this post


Link to post
Share on other sites
Your code does what you wrote it to do. It opens a file, then reads a word from standard input (not from the file) and writes it back to standard input.

Perhaps you intended to write to the file?

std::cin >> text;
file << text;

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!