c++ - 将 int 值附加到字符串?

标签 c++ string variables

<分区>

通过 C++ 实践介绍 CS。

我无法弄清楚如何将玩家 1 和玩家 2 获得的随机数分配给字符串值“p1_string_val”和“p2_string_val”。我在下面显示了到目前为止的代码。

有人可以帮我弄清楚如何将随机数分配给字符串吗?任何进一步的帮助也将受到欢迎!太感谢了。

分配说明: 我已完成第 0 步和第 1 步。我需要帮助将随机数分配给字符串,任何其他帮助都会有所帮助。

我的代码如下所示:
"玩家一有石头/布/剪刀
玩家二有石头/布/剪刀
请按任意键继续”

  1. 根据P1_int_val 和P2_int_val 中存储的数值,使用if、else 和else if 语句将以下字符串存储到P1_string_val、P2_string_val 中。

int_val 0 string_val 岩石
int_val 1 string_val 纸
int_val 2 string_val 剪刀


  #include <fstream>
     #include <iostream>
     #include <string>
     #include <time.h>

     using namespace std; 


      void main()

     {
         int p1_int_val, p2_int_val; 
    string p1_string_val, p2_string_val; 

     srand(time(NULL)); 

     p1_int_val = (rand() % 3);
     p2_int_val = (rand() % 3);

     //to check the random integer are between 0-2 
     /*cout << "Player one has this " << p1_int_val << endl; 
     cout << "Player two has this " << p2_int_val << endl; */


     if (p1_int_val == 0)
         cout << "Player one has rock " << endl; 

     if (p1_int_val == 1)
         cout << "Player one has paper" << endl;

     else if (p1_int_val == 2)
         cout << "Player one has scissors" << endl; 

     if (p2_int_val == 0)
         cout << "Player two has rock " << endl;

     if (p2_int_val == 1)
         cout << "Player two has paper" << endl;


      else if (p2_int_val == 2)
                 cout << "Player two has scissors" << endl;
 return 0; 
         } 

Once the program has been completed it should display:

//Player one has rock/paper/scissors (depends on what number they got)  
//Player two has rock/paper/scissors   
//Player one or two has won OR TIE



最佳答案

如果你想给字符串赋值,当然可以使用std::to_string函数。 std::to_string 自 C++11 以来是标准库的一部分。

std::string random_number = std::to_string(rand()) 

另一种方法,如果处理旧版本的 C++ 是使用 .str(),它是 sstream 库的一部分

std::stringstream ss;
ss << rand();
std::string random_number = ss.str();

关于c++ - 将 int 值附加到字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56640045/

相关文章:

Java模糊字符串与名称匹配

java - 查找字符串中的所有数字

C++ 模板不接受迭代器

c++ - 标准是否保证 string::erase 和 string::pop_back 不重新分配内存?

c++ - 如何将世界坐标转换为屏幕坐标

javascript - 如何将变量从 imacros 传递到 javascript?

shell - 变量没有在 jenkins 管道的 sh 中填充

c - 如何在 C 中使用函数(初学者)

c++ - 是否可以 move boost::optional ?

c++ - VTK 未定义引用