从cin流中读取字符串并存储以空格分隔的值
C++: Read string from cin stream and store values separated by space
实际上我想出了(临时)解决方案,但我仍然认为它可以做得更有效,但如何?我不是很熟悉流(还是c++初学者)。我的观点是使用std::getline()
从std::cin
流读取行(我假设它只能作为字符串读取),所以我试图设置一些std::string::const_iterator
并迭代我的字符串包含的每个字符,使用' '
作为分隔符来区分我的字符串中的不同单词(值)。我将只读取两个用一个空格分隔的整数。
的例子:
输入:结果:2(例数)
10 20 30 40
在变量A
中存储10,在变量B
中存储20,在变量C
中存储30…等等。
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main()
{
bool next;
unsigned short int cases;
long long m, n;
std::vector<long long> vcases;
std::string m_n_store;
std::string m_n_read;
std::cin >> cases;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
for (int i = 0; i < cases; ++i)
{
next = false;
std::getline(std::cin, m_n_read);
for (std::string::const_iterator it = m_n_read.begin(); it != m_n_read.end(); ++it)
{
if (*it == ' ')
{
next = true;
std::istringstream iss(m_n_store);
iss >> m;
vcases.push_back(m);
m_n_store.erase();
}
if (!next) m_n_store.push_back(*it);
else if (*it != ' ') m_n_store.push_back(*it);
if (it == (m_n_read.end() - 1))
{
std::istringstream iss(m_n_store);
iss >> n;
vcases.push_back(n);
m_n_store.erase();
};
}
}
for (int i = 0; i < vcases.size(); ++i)
{
std::cout << vcases[i] << 'n';
}
}
c++流,默认情况下,用空格分隔输入操作。不需要遍历字符串并用空格字符分隔它。您可以使用std::istream_iterator
和vector的范围构造函数:
std::vector<long long> mcases{std::istream_iterator<long long>{std::cin}, {}};
试试这个:
size_t pos = 0;
while ((pos = m_n_read.find(" ")) != std::string::npos) {
std::istringstream iss(m_n_read.substr(0, pos));
iss >> m;
vcases.push_back(m);
m_n_read.erase(0, pos + 1);
}
if (m_n_read.size() > 0)
{
std::istringstream iss(m_n_read);
iss >> m;
vcases.push_back(m);
}
相关文章:
- 将字符串存储在c++中的稳定内存中
- 2D数组来自文本输入,中间有空格
- std::原子加载和存储都需要吗
- C++:将控制台输出存储在宏中更好吗
- 使用QProcess执行命令,并将结果存储在QStringList中
- 访问存储在向量C++中的结构的多态成员
- 如何从存储在std::映射中的std::集中删除元素
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 存储模板类型以强制转换回派生<T>
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 如何存储包含多个空格的字符串 c++
- 获取由空格分隔的未知大小的单行输入,并将其存储到整数数组中
- 如何删除字符串中的所有空格并将数据存储在两者之间
- 如何修改数组,从中删除空格,然后将其存储在新数组中
- 如何查找空格并存储到变量中
- 将包含空格的文件中的文本存储为字符串
- 将用户输入的前两个单词分隔一个空格,然后存储剩余短语(C++)
- 从cin流中读取字符串并存储以空格分隔的值
- 存储由空格分隔的字母矩阵
- 我将如何使用 cin 读取一行用户输入,将该行拆分为空格,并将这些标记存储到字符串数组中