C++ help

Started by
17 comments, last by Xai 17 years, 8 months ago
How do I have some one enter a filename and then open that file for input/output in C++?
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());
why is there "std::" in front of "cout" is that nesisary for the code to work?
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.
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).
I got a compiler eror on this line:

if (!std::cin) return;


saying:

return-statement with no value, in function return 'int'
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.
#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...
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;
It isn't working... maybe I'm not using a good compiler... I use bloodshed dev-C++

This topic is closed to new replies.

Advertisement