gpt4 book ai didi

c++ - 如何在 C++ 中为 cin.ignore() 指定多个分隔符?

转载 作者:行者123 更新时间:2023-12-04 17:23:38 25 4
gpt4 key购买 nike

以下是我的代码:

// Program to print the initials of a name
#include <iostream>
using namespace std;

int main() {
char first, last;
cout<<"Enter first and last name: ";
first = cin.get();
cin.ignore(10000,' ');
last = cin.get();
cout<<first<<" "<<last;
return 0;
}

我正在寻找一种方法来指定多个分隔符作为 cin.ignore() 的第二个参数,例如cin.ignore(10000,'\n' or ' ')。有办法实现吗?

最佳答案

最简单的方法就是peek()下一个字符,检查它是否在定界符列表中,如果不在则忽略它:

while (std::cin.peek() != '\n' && std::cin.peek() != ' ' && !std::cin.eof())
std::cin.ignore(1);

或者:

char delim[] = { ' ', '\n' };
int delim_len = sizeof(delim) / sizeof(char);
while( std::find(delim, delim+delim_len, std::cin.peek()) == delim+delim_len) && !std::cin.eof() )
std::cin.ignore(1);

来自 cplusplus.com :

int peek();

Peek next character.

Returns the next character in the input sequence, without extracting it: The character is left as the next character to be extracted from the stream.

If any internal state flags is already set before the call or is set during the call, the function returns the end-of-file value (EOF).

注意:来自std::istream::ignore引用资料,也在 cplusplus.com 上,我们可以看到,仅提供一个参数即可将 ignore() 分隔符默认设置为 EOF:

istream& ignore (streamsize n = 1, int delim = EOF);

关于c++ - 如何在 C++ 中为 cin.ignore() 指定多个分隔符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64765238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com