learn/doc/cpp_input_output at main · gitLibs/learn · GitHub
Skip to content

Latest commit

 

History

History
 
 

Folders and files

README.md

back to contents

C++: input, output

↑ top




input, output

#include <iostream>
using namespace std;

int main ()
{
	int i;
	cout << "Please enter an integer value: ";
	cin >> i;
	cout << "The value you entered is " << i;
	cout << " and its double is " << i*2 << ".\n";
}

/*
Please enter an integer value: 111
The value you entered is 111 and its double is 222.
*/

↑ top




exist

#include <iostream>
using namespace std;
#include <sys/stat.h>

inline bool isExist (const string& name) {
	struct stat buffer;
	return (stat (name.c_str(), &buffer) == 0); 
}

int main()
{
	cout << isExist("./testdata/sample.txt") << endl; // 1
}

↑ top




write, read

#include <iostream>
#include <fstream>
// #include <stdio.h>
#include <cstdio>
using namespace std;

int main () {

	string fpath = "example.txt";

	ofstream fw;
	fw.open (fpath);
	fw << "Hello World!\n";
	fw << "C++\n";
	fw.close();

	string line;
	ifstream fi (fpath);
	if (fi.is_open())
	{
		while ( getline (fi, line) )
		{
			cout << line << endl;
		}
		fi.close();
	}
	else cout << "Unable to open file" << endl;

	if( remove( fpath.c_str() ) != 0 )
		perror( "Error deleting file" );
	else
		puts( "File successfully deleted" );
}

/*
Hello World!
C++
File successfully deleted
*/

↑ top