itoa dziwne wyniki

0

mam problem... chcę zapisać do stringa inta ale tak żeby

cout << string 

wyglądało tak samo jak cout << int

 a mi dodaje f albo jakieś zera jak mam itoa.. jak to zrobic? Bo chcę zapisać liczby do pliku a plik.write porzebuje stringa
2
int x;
std::string y;
x= strtol(y.c_str(), NULL, 10);

EDIT:

int x;
std::string y;
template <class T> std::string ToString(const T& t) 
{ 
    std::ostringstream oss; 
    oss << t; 
    return oss.str(); 
} 

y = ToString (x);
1

Nie używaj plik.write;

ofstream fout("plik.txt");
fout<<"Ala ma "<<N<<" kotów"<<endl;
0

@Kamil9132 spoko ale ograniczasz się do 1 argumentu i streama;

a z tym możesz czynić cuda;

możesz podać fstream tak jak @_13th_Dragon pokazał

#include <iostream>
#include <sstream>

template<typename T, typename... Args>
void toStream(T& stream, Args... args)
{
	bool dummy[] = { (stream << args, true)... };
}

int main()
{
	std::stringstream s;
	toStream(s, 1, "abc", 2, "lol");
	std::cout << s.str();

	std::cout << "\nlub\n";

	toStream(std::cout, 1, "abc", 2, "lol");

	return 0;
}

http://ideone.com/RQ4clY

4

tak btw jaki sens ma tworzenie tego toStream ? skoro można po prostu:

#include <iostream>
#include <sstream>

int main() {
	std::stringstream s;
	s << 1 << "abc" << 2 << "lol";
	std::cout << s.str();
	return 0;
}
0
#include <boost/lexical_cast.hpp>

...
int i = 42;
string s = boost::lexical_cast<string>(i);

:-]

1 użytkowników online, w tym zalogowanych: 0, gości: 1