IT

C ++에서 문자열에 int를 어떻게 추가합니까?

lottoking 2020. 6. 14. 10:10
반응형

C ++에서 문자열에 int를 어떻게 추가합니까? [복제]


이 질문에는 이미 답변이 있습니다.

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);

cout을 사용하면 다음과 같이 정수를 직접 쓸 수 있습니다.

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는 내장 유형 캐스트와 같은 구문으로 문자열 스트림 변환을 래핑합니다.

#include <boost/lexical_cast.hpp>

text += boost::lexical_cast<std::string>(i);

이것은 다른 방법으로도 작동합니다. 즉, 문자열을 구문 분석합니다.


printf("Player %d", i);

(내 대답을 원하는대로 공감하십시오. 나는 여전히 C ++ I / O 연산자를 싫어합니다.)

:-피


이것들은 일반적인 문자열에서 작동합니다 (파일 / 콘솔로 출력하고 싶지 않지만 나중에 사용하기 위해 저장하는 경우).

boost.lexical_cast

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 << text << i;

여기서 한 가지 방법은 문제에 필요한 경우 출력을 직접 인쇄하는 것입니다.

cout << text << i;

Else, one of the safest method is to use

sprintf(count, "%d", i);

And then copy it to your "text" string .

for(k = 0; *(count + k); k++)
{ 
  text += count[k]; 
} 

Thus, you have your required output string

For more info on sprintf, follow: http://www.cplusplus.com/reference/cstdio/sprintf


cout << text << i;

The << operator for ostream returns a reference to the ostream, so you can just keep chaining the << operations. That is, the above is basically the same as:

cout << text;
cout << i;

cout << "Player" << i ;

cout << text << " " << i << endl;

You also try concatenate player's number with std::string::push_back :

Example with your code:

int i = 4;
string text = "Player ";
text.push_back(i + '0');
cout << text;

You will see in console:

Player 4


The easiest way I could figure this out is the following..
It will work as a single string and string array. I am considering a string array, as it is complicated (little bit same will be followed with string). I create a array of names and append some integer and char with it to show how easy it is to append some int and chars to string, hope it helps. length is just to measure the size of array. If you are familiar with programming then size_t is a 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;
        }


}

There are a few options, and which one you want depends on the context.

The simplest way is

std::cout << text << i;

or if you want this on a single line

std::cout << text << i << endl;

If you are writing a single threaded program and if you aren't calling this code a lot (where "a lot" is thousands of times per second) then you are done.

If you are writing a multi threaded program and more than one thread is writing to cout, then this simple code can get you into trouble. Let's assume that the library that came with your compiler made cout thread safe enough than any single call to it won't be interrupted. Now let's say that one thread is using this code to write "Player 1" and another is writing "Player 2". If you are lucky you will get the following:

Player 1
Player 2

If you are unlucky you might get something like the following

Player Player 2
1

The problem is that std::cout << text << i << endl; turns into 3 function calls. The code is equivalent to the following:

std::cout << text;
std::cout << i;
std::cout << endl;

If instead you used the C-style printf, and again your compiler provided a runtime library with reasonable thread safety (each function call is atomic) then the following code would work better:

printf("Player %d\n", i);

Being able to do something in a single function call lets the io library provide synchronization under the covers, and now your whole line of text will be atomically written.

For simple programs, std::cout is great. Throw in multithreading or other complications and the less stylish printf starts to look more attractive.


You can use the following

int i = 4;
string text = "Player ";
text+=(i+'0');
cout << (text);

If using Windows/MFC, and need the string for more than immediate output try:

int i = 4;
CString strOutput;
strOutput.Format("Player %d", i);

참고URL : https://stackoverflow.com/questions/64782/how-do-you-append-an-int-to-a-string-in-c

반응형