我正在尝试创建一个程序,提示用户输入一个字符串来创建一个非常简单的动画。我的代码工作正常,但是,当我试图显示字符串时,我无法让它工作(第二个功能)请帮助!
#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++);
}
答案 0 :(得分:1)
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&amp; animation)