【问题标题】:How to turn console outputted characters into a string; c++如何将控制台输出的字符变成字符串; C++
【发布时间】:2014-03-06 02:25:27
【问题描述】:

我想获取一系列字符并将它们分配给一个字符串变量。

这里是我的 C++ 代码的摘录,然后是对问题的进一步描述。

#include <iostream>
#include <string>
using namespace std;


int main () {

   string line = "MJQQT BTWQI";

   int shift = 5;
   int oldShift = 5;
   int count = 0;

   cout << "Enter your string to shift: ";
   getline(cin,line);
   cout << "Enter your shift number: ";
   cin >> shift;
   oldShift = shift;

   while(count < line.length())
   {


        if(line[count] != ' '){

                if((line[count]-shift) < 'A')
                    shift -= 26;


            line[count] = line[count] - shift;
            shift = oldShift;
            cout << line[count];

        } else{ line[count] = ' ';
            cout << line[count];
        }
    count++;
   }




   return 0;
}

输出如下:

输入要换档的字符串:HELLO

输入你的班次值:5

CZGGJ

我想知道如何将在此循环中一次打印出的单个字符分配给一个新字符串。例如,所需的字符串是

newString = "CZGGJ"

【问题讨论】:

    标签: c++ string text character line


    【解决方案1】:

    首先,声明一个字符串,即string stringOfChars;。一旦你这样做了,无论你在哪里写cout &lt;&lt; line[count];,在它下面写stringOfChars = stringOfChars + line[count];

    【讨论】:

      【解决方案2】:

      声明类似

      std::string newString = "";
      

      然后在cout语句之后或之前写

      newString = newString + line[count];
      

      【讨论】:

        猜你喜欢
        • 2011-05-16
        • 1970-01-01
        • 1970-01-01
        • 2011-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-09
        • 1970-01-01
        相关资源
        最近更新 更多