如何遍历整个字符串并一次播放一个字符C++
How to loop through a total string and diplay one character at a time C++
我正在尝试创建一个程序,提示用户输入字符串以创建非常简单的动画。我的代码工作正常,但是,当我尝试显示字符串时,我无法完全让它工作(第二个功能)请帮忙!
#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)
相关文章:
- 为什么完整的字符串没有一次打印,但是当我尝试逐个字符打印时
- 如何从文本文件中一次读取一个字符
- 尝试一次将单个字符读取到大小不确定的数组中
- 一次读取一个字符的文件,直到使用 read(2) 和 write(2) 换行符
- 为什么一次打印一个字符比提前连接它们慢
- 尝试一次读取一个字符的矩阵
- 如何修复密码条目,它一次输入两个字符
- 至少包含一次字符 X 的 S 的不同子字符串的数量
- 仅当捕获组最后一次出现时,才使字符成为可选字符
- 在将数组与字符数组进行比较后需要帮助输出一次结果
- 如何一次对 3 个字符使用 switch 语句
- C++一次打印一个单词的字符串,计算字符数和字符数
- 在C++中一次一行地从文本文件中读取int(好的字符,然后转换)时出现问题
- 一次读取一个字符的字符串,直到行或文件末尾
- 删除字符C++最后一次出现时字符数组的开头
- 如何遍历整个字符串并一次播放一个字符C++
- 一次C++两个字符的字符到二进制转换,以获得 16 位二进制形式
- 如何从字符串中一次选择两个字符?到达字符串的第 i 个位置
- C++:一次阅读一个字符,直到一行的末尾不起作用
- 我正在阅读文件,但在阅读时,它是阅读最后一个字符一次额外