问题描述
James brown /n
Peter Lee /n
Chris Wu /n
Steven Huang /n
Kelly Yang /n
首先,我需要知道输入流中最长的名称有多长时间,然后需要创建一个动态的二维char数组。最后,将名称放入动态数组中。(在这种情况下,我需要创建5 * 12数组,因为“ Steven Huang”中有12个字母。)
我如何才能读取输入流来知道数字'12',却不提取它们以使用C ++中的cin>>
将其放入数组中?
所有建议将不胜感激。
解决方法
我想“最简单”的答案是仅使用cin找出单个字符。即使这不是一种有效的语言,但您似乎对学习基本语言更感兴趣,因此它可能有助于您遵循自己的思路。
char c;
std::string s;
std::vector<std::string> vector_of_strings;
while(cin >> c)
{
s = s + c;
if ( c == '\n')
{
vector_of_strings.emplace_back(s);
s = "";
}
}
那么您就可以遍历vector_of_strings,检查每个长度并进行后期处理。
另一种尝试方法是尝试std::getline
#include <sstream>
std::string line;
std::vector<std::string> vector_of_strings;
std::getline(std::cin,line);
while(line.length() > 0) //stop when user enters empty line
{
std::getline(std::cin,line);
vector_of_strings.emplace_back(line);
}
,然后再进行一些后处理
,您需要提取字符,然后解压缩它们。为此,您需要考虑字符的读取并解压缩该数量的字符。示例:
int read = 20;
std::string data;
// Get 20 characters
for (int i = 0; i < read; i++) {
data += std::cin.get();
}
// Unget 20 characters
for (int i = 0; i < read; i++) {
std::cin.unget();
}
此代码从std::cin
中读取20个字符,并将它们存储在变量data
中,然后解压缩20个字符,从而使流进入其先前状态。