Site Tools


cppexample

Проверка на корретктность ввода

#include <iostream>
using namespace std;
      
      void main(){
	int i;
	cin.unsetf(ios::skipws);
	while(true){
		cout << "\nEnter an integer: ";
		cin >> i;
		if( cin.good() ){
			cin.ignore(10, '\n');          // remove newline
			break;                         // exit loop
		}
	cin.clear();                      // clear the error bits
	cout << "Incorrect input";
	cin.ignore(10, '\n');             // remove newline
	}
cout << "integer is " << i;          // error-free integer
} 

Запись в файл

// formato.cpp
// writes formatted output to a file, using <<
#include <fstream>                //for file I/O
#include <iostream>
#include <string>
using namespace std;
      
int main()
{
	char ch = 'x';
	int j = 77;
	double d = 6.02;
	string str1 = "Kafka";         //strings without
	string str2 = "Proust";        //   embedded spaces
	ofstream outfile("fdata.txt"); //create ofstream object
	outfile << ch                  //insert (write) data
	<< j
	<< ' '                 //needs space between numbers
	<< d
	<< str1
	<< ' '                 //needs spaces between strings
	<< str2;
	cout << "File written\n";
	return 0;
}

Чтение из файла до пробела

// formati.cpp
// reads formatted output from a file, using >>
#include <fstream>                 //for file I/O
#include <iostream>
#include <string>
using namespace std;
      
int main()
{
	string str1;
	ifstream infile("fdata.txt");   //create ifstream object
	infile >>  str1;
	cout  << str1 << endl;
	return 0;
}

По линиям:

#include <fstream>                  //for file functions
#include <iostream>
using namespace std;
int main()
{
	const int MAX = 80;              //size of buffer
	char buffer[MAX];                //character buffer
	ifstream infile("fdata.txt");     //create file for input
	while( !infile.eof() )           //until end-of-file
	{
		infile.getline(buffer, MAX);  //read a line of text
		cout << buffer << endl;       //display it
	}
	return 0;
}

Запись\чтение данных объекта в файл (добавление)

	void Fwrite(){
		  fstream MyFile;
		  MyFile.open("Distance.data", ios::app | ios::out);
		  MyFile.write( (char*)(this), sizeof(*this) );
		  MyFile.close();
	}
	void Fread(){
		fstream MyFile;
		MyFile.open("Distance.data", ios::in);
		while(MyFile){
			MyFile.read( (char*)(this), sizeof(*this) );
			this->showdist();
			cout << endl;
		}
		MyFile.close();
	}

Посимвольное копирование файла

#include <iostream>
#include <fstream>
#include "stdlib.h"

using namespace std;

class CopyFile{
private:
	char* SourceFile;
	char* DestFile;

public:
	void Copy(char* s, char* d){
		SourceFile = s;
		DestFile = d;
		char buffch;
		if(SourceFile){
			if(DestFile){
				fstream Sfile(SourceFile, ios::in);
				if(!Sfile){cout << "Error in open source file" << endl ; exit(0);}
				fstream Dfile(DestFile, ios::out);
				if(!Sfile){cout << "Error in open destination file" << endl ; exit(0);}
				while(Sfile){
					Sfile.get(buffch);
					Dfile.put(buffch);
				}
			
			}else{cout << "Errof if DestFile" << endl;}
		}else{cout << "Error if SourceFile" << endl;}
	}
};

void main(int argc, char* argv[]){
	if(argc == 3){

		CopyFile CopyObj;
		cout << "Copy " << argv[1] << " to " << argv[2] << " ..." << endl;
		CopyObj.Copy(argv[1], argv[2]);
		cout << "Done" << endl;

	}else{cout << "Use MyCopy.exe SourceFile DestFile" << endl;}
	
}

Определяем размер файла в байтах

#include <iostream>
#include <fstream>
#include "stdlib.h"
using namespace std;
void main(int argc, char* argv[]){
	if(argc != 2){cout << "Use wsize filename" << endl; exit(0);}
	int size;
	fstream File(argv[1], ios::in);
	if(!File){cout << "Error in open file" << endl; exit(0);}
	File.seekg(0, ios_base::end);
	size = File.tellg();
	cout << "Size file: " << size << " bite" << endl;
}

Поиск в массиве

#include <iostream>
#include <algorithm>
using namespace std;
int arr[] = { 1 , 22, 33, 44, 55, 66, 76, 64, 34 ,23};
void main(){
	int* ptr;
	ptr = find(arr, arr+10, 33);
	cout << "ptr=" << ptr << endl
		<< "arr=" << arr << endl
		<< "(ptr - arr)=" << (ptr - arr) << endl;
} 
Вывод:
C:\CPP>tmptest.exe
ptr=01130008
arr=01130000
(ptr - arr)=2

Random

#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int main(){
	srand(time(NULL));
	for(int i = 0; i <= 100 ; i++){
	  cout << "i" << i << "=" << rand() % 100 << endl; // %100 для получения значения от 0 до 100
	}
}

ForNew

You could leave a comment if you were logged in.
cppexample.txt · Last modified: 2012/07/13 19:19 by konovalov

Page Tools