int i = 4;
string text = "Player ";
cout << (text + i);
Player 4
를 인쇄하고 싶습니다.
위의 내용은 분명히 잘못되었지만 여기서 내가하려고하는 것을 보여줍니다. 이 작업을 수행하는 쉬운 방법이 있습니까? 아니면 새 포함을 추가해야합니까?
C++ 11에서는 다음과 같이 작성할 수 있습니다.
#include <string> // to use std::string, std::to_string() and "+" operator acting on strings
int i = 4;
std::string text = "Player ";
text += std::to_string(i);
글쎄, 만약 당신이 정수를 쓸 수있는 법을 사용하여 직접 그것에,
std::cout << text << i;
모든 종류의 객체를 문자열로 변환하는 C++ 방식은 문자열 스트림 을 통해 이루어집니다. 편리하지 않으면 그냥 만드십시오.
#include <sstream>
std::ostringstream oss;
oss << text << i;
std::cout << oss.str();
또는 정수를 변환하여 문자열에 추가 할 수 있습니다.
oss << i;
text += oss.str();
마지막으로, Boost 라이브러리는 boost::lexical_cast
를 제공합니다.이 라이브러리는 stringstream 변환을 기본 제공 형식 캐스트와 같은 구문으로 둘러 쌉니다.
#include <boost/lexical_cast.hpp>
text += boost::lexical_cast<std::string>(i);
이것은 또한 다른 방법으로, 즉 문자열을 파싱하기 위해 작동합니다.
printf("Player %d", i);
(내 대답을 모두 downvote 내 대답, 나는 여전히 C + + I/O를 연산자가 싫어.)
:-피
이것들은 일반적인 문자열을 위해 작동합니다 (파일/console로 출력하고 싶지는 않지만 나중에 사용하기 위해 저장하십시오).
부스트. 익스 클루 시브 _ 캐스트
MyStr += boost::lexical_cast<std::string>(MyInt);
문자열 스트림
//sstream.h
std::stringstream Stream;
Stream.str(MyStr);
Stream << MyInt;
MyStr = Stream.str();
// If you're using a stream (for example, cout), rather than std::string
someStream << MyInt;
실제로 출력되기 전에 문자열을 만들고 싶다면 std::stringstream
를 사용할 수도 있습니다.
cout << text << " " << i << endl;
귀하의 예제는 정수가 뒤에 오는 문자열을 표시하고자 함을 나타내는 것 같습니다.
string text = "Player: ";
int i = 4;
cout << text << i << endl;
잘 될 것입니다.
그러나 문자열 위치를 저장하거나 전달하는 경우 빈번하게 수행하면 덧셈 연산자에 과부하가 발생할 수 있습니다. 나는 이것을 아래에 설명한다.
#include <sstream>
#include <iostream>
using namespace std;
std::string operator+(std::string const &a, int b) {
std::ostringstream oss;
oss << a << b;
return oss.str();
}
int main() {
int i = 4;
string text = "Player: ";
cout << (text + i) << endl;
}
실제로 템플릿을 사용하여이 접근 방식을보다 강력하게 만들 수 있습니다.
template <class T>
std::string operator+(std::string const &a, const T &b){
std::ostringstream oss;
oss << a << b;
return oss.str();
}
이제 b
객체가 정의 된 스트림 출력을 갖는 한 문자열 (또는 적어도 사본)에 추가 할 수 있습니다.
또 다른 가능성은 Boost.Format :
#include <boost/format.hpp>
#include <iostream>
#include <string>
int main() {
int i = 4;
std::string text = "Player";
std::cout << boost::format("%1% %2%\n") % text % i;
}
여기에 작은 변환/추가 예제가 있는데, 전에 필자가 필요로했던 몇 가지 코드가 있습니다.
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main(){
string str;
int i = 321;
std::stringstream ss;
ss << 123;
str = "/dev/video";
cout << str << endl;
cout << str << 456 << endl;
cout << str << i << endl;
str += ss.str();
cout << str << endl;
}
출력은 다음과 같습니다.
/dev/video
/dev/video456
/dev/video321
/dev/video123
마지막 두 줄에서는 수정 된 문자열이 실제로 출력되기 전에 저장하고 필요할 경우 나중에 사용할 수 있습니다.
기록을 위해 Qt의 QString
클래스를 사용할 수도 있습니다 :
#include <QtCore/QString>
int i = 4;
QString qs = QString("Player %1").arg(i);
std::cout << qs.toLocal8bit().constData(); // prints "Player 4"
cout << "Player" << i ;
cout << text << i;
한 가지 방법은 문제에 필요한 경우 출력을 직접 인쇄하는 것입니다.
cout << text << i;
그렇지 않으면 가장 안전한 방법 중 하나는
sprintf(count, "%d", i);
그런 다음 "텍스트"문자열에 복사하십시오.
for(k = 0; *(count + k); k++)
{
text += count[k];
}
따라서 필요한 출력 문자열이 있습니다.
sprintf
에 대한 자세한 내용은 다음을 참조하십시오. http://www.cplusplus.com/reference/cstdio/sprintf
cout << text << i;
Ostream에 대한 <<
연산자는 ostream에 대한 참조를 반환하므로 <<
연산을 계속 체인화 할 수 있습니다. 즉 위의 내용은 기본적으로 다음과 같습니다.
cout << text;
cout << i;
cout << text << " " << i << endl;
또한 std::string::Push_back
를 사용하여 플레이어 번호를 연결해보십시오.
코드 예제 :
int i = 4;
string text = "Player ";
text.Push_back(i + '0');
cout << text;
콘솔에서 볼 수 있습니다 :
선수 4
내가 알아낼 수있는 가장 쉬운 방법은 다음과 같습니다.
단일 문자열 및 문자열 배열로 작동합니다. 나는 문자열 배열을 고려하고 있는데, 복잡하기 때문에 (조금은 똑같은 문자열을 따를 것이다). 나는 배열의 이름을 만들고 append 어떤 정수와 char을 추가하여 얼마나 쉽게 추가 할 수 있는지 보여줍니다 int and chars to string, 도움이되기를 바랍니다. 길이는 단지 배열의 크기를 측정하는 것입니다. 프로그래밍에 익숙하다면 size_t는 unsigned int입니다.
#include<iostream>
#include<string>
using namespace std;
int main() {
string names[] = { "amz","Waq","Mon","Sam","Has","Shak","GBy" }; //simple array
int length = sizeof(names) / sizeof(names[0]); //give you size of array
int id;
string append[7]; //as length is 7 just for sake of storing and printing output
for (size_t i = 0; i < length; i++) {
id = Rand() % 20000 + 2;
append[i] = names[i] + to_string(id);
}
for (size_t i = 0; i < length; i++) {
cout << append[i] << endl;
}
}