获取输出并将其存储到变量中
Taking output and storing it into a variable?
我有这个代码:
string text;
getline(cin ,text);
istringstream iss(text);
copy(
istream_iterator<string>(iss),
istream_iterator<string>(),
ostream_iterator<string>(cout,"n")
);
当我输入一个字符串时:bf "inging" filename
,它输出:
bf
"inging"
filename
有没有办法让我获取每个单独的输出并将其保存到变量中?
当然可以捕获不同的输出并对其进行处理:您将创建一个流缓冲区来检测换行符并对自上次换行符以来收到的字符执行某些操作。只有这样,您才会将字符串转发到其他地方。虽然可行,但我怀疑这真的是你想做的。
如果你想从流中捕获所有std::string
,并且你不希望每个都有一个特定的名称,例如,因为你不知道需要多少个字符串,你可以将它们存储到std::vector<std::string>
中使用
std::vector<std::string> strings{ std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>() };
。或
std::vector<std::string> strings;
std::copy(std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>(),
std::back_inserter(strings));
如果你想让字符串在单个变量中,你只需将它们读入变量并确保你读取所有变量:
std::string a, b, c;
if (iss >> a >> b >> c) {
std::cout << "read a='" << a << "' b='" << b << " c='" << c << "'n";
}
else {
std::cout << "failed to read three strings from line '" << text << "'n";
}
相关文章:
- 为什么我可以将变量存储在不是其最小对齐方式的倍数的地址?
- 如何将变量存储为无
- 有没有办法强制C++编译器将变量存储在寄存器中?
- C++ - thread_local变量存储在哪里?
- 如何使用 c++ 将多个变量存储在一个变量中?例如,双精度 x,y,z 包含在可变点 p 中
- 如何将文件从文件作为变量存储
- 引用变量存储在哪里
- 尝试在C 程序中设置简单的键盘输入.使用变量存储True或false
- 如何将变量存储在另一个文件中
- 编译时局部变量存储在哪里
- lambda 捕获的变量存储在哪里
- 闭包捕获的变量存储在哪里?
- 静态和全局变量存储说明
- 模式名称,将值作为静态变量存储在函数中
- 任何人都能解释常量或常量变量存储在哪里吗
- 将变量存储在将被多次使用的函数中的最佳方式(c++)
- 如何将字符变量存储为二维字符变量
- 将环境变量存储在动态分配的数组中
- 从矢量中获取选定的数据,然后作为变量存储
- DLL的全局变量存储在内存中