C++ 如何循环整个字符串并一次显示一个字符C++;
我试图创建一个程序,提示用户输入一个字符串来创建一个非常简单的动画。我的代码工作正常,但是,当我试图显示字符串时,我无法让它正常工作(第二个函数),请帮助C++ 如何循环整个字符串并一次显示一个字符C++;,c++,C++,我试图创建一个程序,提示用户输入一个字符串来创建一个非常简单的动画。我的代码工作正常,但是,当我试图显示字符串时,我无法让它正常工作(第二个函数),请帮助 #include <iostream> #include <string> #include <cmath> using namespace std; void getAnimation(string& animation); void displayAnimation(string&a
#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++);
}
#包括
#包括
#包括
使用名称空间std;
void getAnimation(字符串和动画);
void显示动画(字符串和动画);
int main()
{
弦乐动画;
动画(动画);;
显示动画(动画);
返回0;
}
//要求用户输入单个帧
//作为字符串返回
//输入参数:帧数、线数和动画
//返回:动画(字符串)
void getAnimation(字符串和动画)
{
int计数器、行、i、numLines、frameNum;
努姆林宫;
//有助于for-loop的数字
计数器=0;
frameNum=1;
//for-loop获取信息
用于(计数器=0;计数器 cout动画
是一个字符串
不是数组,因此for(auto c:animation)
不起作用。要获得单个角色,只需执行动画。at(i)
其中i
是所需角色的索引
您还可以使用stringstream
char c;
std::istringstream iss(animation)
while (iss.get(c))
{
// Do animation here
}
不要忘记包括sstream
char c;
std::istringstream iss(animation)
while (iss.get(c))
{
// Do animation here
}
您的代码中还有另一个问题。您希望动画
能够保存多行输入,对吗?因为动画
是std::string
而不是我之前提到的数组或向量
,您应该使用<代码>标准::向量
用于您的方法
因此,像Sostd::vector animation
那样声明动画,然后在getAnimation
中,您需要执行以下操作:
for (i = 0; i < lines; ++i)
{
cout << "Give me line of frame #" << frameNum++ << endl;
string tmp;
cin >> tmp;
animation.push_back(tmp);
}
您还需要将函数声明更改为
void getAnimation(vector&animation)
和`void displayAnimation(vector&animation)`所面临的确切问题是什么?程序只输出我键入的最后一个字符,而不是整个字符串。放置在getAnimation
中的animation
中的最后一个值是返回到main()
,然后在那里传递它(并且只传递它)要显示动画
,请更改代码。