如何遍历整个字符串并一次播放一个字符C++

How to loop through a total string and diplay one character at a time C++

本文关键字:字符 一次 播放 一个 C++ 何遍历 串并 字符串 遍历      更新时间:2023-10-16

我正在尝试创建一个程序,提示用户输入字符串以创建非常简单的动画。我的代码工作正常,但是,当我尝试显示字符串时,我无法完全让它工作(第二个功能)请帮忙!

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

void getAnimation(string& animation);
void displayAnimation(string& animation);
int main()
{
  string animation;
  getAnimation(animation);
  displayAnimation(animation);
  return 0;
}

//Ask user to enter a single frame 
//returned as string
//Input Parameters: Numeber of Frames, Number of Lines, and Animation 
//Returns: The animation (string)
void getAnimation(string& animation)
{
  int counter, lines, i, numLines, frameNum;
  cout << "How many frames of animation would you like?" << endl;
  cin >> numLines;
  // numbers to help with for - loop
  counter = 0;
  frameNum = 1;
  //for - loop to get information
  for (counter = 0; counter < numLines; counter++)
  {
    cout << "How many lines do you want in this frame?" << endl;
    cin >> lines;
    for (i = 0; i < lines; ++i)
    {
      cout << "Give me line of frame #" << frameNum++ << endl;
      cin >> animation;
      //getline(cin, animation);
      //cin.ignore();
    }
  }
}
//Will gather the string received in main and gather it here to display
//Returned full animation
//Input Parameters: None
//Output Parameters: Animation
void displayAnimation(string& animation)
{
  cout << "Here is your super-sweet animation!n";
  // to print out entire animation
  //for (auto c : animation)
    //cout << animation << endl;
  //for (int i = 0; i < animation.length(); i++);
}

animation是一个string而不是一个数组,因此for (auto c : animation)不起作用。要获得单个字符,只需animation.at(i) 其中i是您想要的字符的索引。

您也可以使用stringstream .

char c;
std::istringstream iss(animation)
while (iss.get(c))
{
  // Do animation here
}

并且不要忘记包括sstream.


您的代码中还有另一个问题。你希望animation持有几行输入,对吧?由于aninamtion是一个std::string而不是一个数组或vector正如我在您使用之前提到的,使用 cin >> animation 覆盖其值的孔时间。您应该为您的方法使用std::vector<string>

因此,像

这样std::vector<string> animation声明动画,getAnimation然后您需要执行以下操作:

for (i = 0; i < lines; ++i)
{ 
   cout << "Give me line of frame #" << frameNum++ << endl;
   string tmp;
   cin >> tmp;
   animation.push_back(tmp);
}

displayAnimation中,您应该首先遍历vector,然后循环遍历它存储的strings以获取单个字符。

for (size_t i = 0; i < animation.size(); ++i)
{
  istringstream iss(animation.at(i));
  char c;
  while (iss.get(c))
  {
    cout << c;
  }
} 

您还需要将函数声明更改为void getAnimation(vector<string>& animation)和'void displayAnimation(vector&animation)