c++不是用getline()而是用cin输入a
c++ inputing a not with getline() but with cin
输入一个带空格的字符串!
我是这么想的:
string name;
std::cout << "Please enter your full name: ";
std::cin >> std::noskipws;
while (std::cin >> name >> std::ws) {
full_name += name + " ";
}
说你的名字是Bill Billy Bobby Bronson Billson
或者可以加上:
if (name == "n")
break;
对于getline(),它是一个语句。但是,出于研究的原因,我不想使用getline()。
可以做到吗?
更新:
如果我尝试我的代码,我得到一个无限循环,无论我改变什么
我不明白你为什么真的想这样做,但是,这是可能的。
operator>>
(std::string
)读取输入字符,直到遇到空白字符。流有一个ctype facet,用来确定一个字符是否为空白。
在这种情况下,您需要一个ctype facet, 仅将n
分类为空白。
struct line_reader: std::ctype<char> {
line_reader(): std::ctype<char>(get_table()) {}
static std::ctype_base::mask const* get_table() {
static std::vector<std::ctype_base::mask>
rc(table_size, std::ctype_base::mask());
rc['n'] = std::ctype_base::space;
return &rc[0];
}
};
您使用包含ctype facet的区域设置实例来填充您的输入文件:
int main() {
std::vector<std::string> lines;
// Tell the stream to use our facet, so only 'n' is treated as a space.
std::cin.imbue(std::locale(std::locale(), new line_reader()));
// to keep things at least a little interesting, we'll copy lines from input
// to output if (and only if) they contain at least one space character:
std::copy_if(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(std::cout, "n"),
[](std::string const &s) {
return s.find(' ') != std::string::npos;
});
}
这里我使用了std::istream_iterator
,它使用指定类型的提取操作符(在本例中为std::string
)来读取数据。
相关文章:
- 我无法在Visual Studio代码中使用CIN输入答案,它说输入您的年龄,但它说只读文本编辑器如何解决这个问题?
- 分割错误 11:尝试使用 cin 输入 B[1] 时
- 当使用 std::CIN 输入结构时,它会出错
- C ++如何使用CIN输入这样的值?
- 使用 cin 输入数组值
- 当我输入一个字母时,cin 输入(输入是一个 int),而不是打印错误一次,它打印正确一次,然后在循环的其余部分打印 i
- 成功使用连续同时(cin >>输入)
- 连续 cin 输入在C++中的工作原理
- 无法获取哨兵值以读取多个 CIN 输入?
- 我如何使用CIN输入整数,每个数字都被逗号分隔
- C CIN输入要文件
- C++:获取用户通过cin输入的数据类型
- 无法读取字符串的长 cin 输入
- 如何将可编辑的预定义字符串写入 C++ 控制台应用程序中的 cin 输入运算符
- 循环获得CIN输入
- cin 输入可以有多大
- 如何拆分 CIN 输入
- 检查有效的 CIN 输入时出现问题
- 较长的获取线 CIN 输入的问题
- 检查 cin 输入流会生成一个整数