假设我们有一个代码:
int main()
{
char a[10];
for(int i = 0; i < 10; i++)
{
cin>>a[i];
if(a[i] == ' ')
cout<<"It is a space!!!"<<endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如何从标准输入中删除空格符号?如果你写空间,程序会忽略!:(是否有任何符号组合(例如'\ s'或类似的东西),这意味着我可以从我的代码的标准输入中使用"空间"?
rco*_*yer 42
默认情况下,它会跳过所有空格(空格,制表符,新行等).您可以更改其行为,也可以使用稍微不同的机制.要更改其行为,请使用操纵器noskipws
,如下所示:
cin >> noskipws >> a[i];
Run Code Online (Sandbox Code Playgroud)
但是,既然你似乎想要查看单个字符,我建议get
在循环之前使用这样的字符
cin.get( a, n );
Run Code Online (Sandbox Code Playgroud)
注意: get
如果找到换行符char(\n
)或n-1个字符后,将停止从流中检索字符.它会提前停止,以便它可以将null字符(\0
)附加到数组中.您可以在此处阅读有关istream
界面的更多信息.
sbi*_*sbi 18
#include <iostream>
#include <string>
int main()
{
std::string a;
std::getline(std::cin,a);
for(std::string::size_type i = 0; i < a.size(); ++i)
{
if(a[i] == ' ')
std::cout<<"It is a space!!!"<<std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用cin.get()
读取下一个字符。
但是,对于这个问题,一次读取一个字符是非常低效的。使用istream::read()
来代替。
int main()
{
char a[10];
cin.read(a, sizeof(a));
for(int i = 0; i < 10; i++)
{
if(a[i] == ' ')
cout<<"It is a space!!!"<<<endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
并用于==
检查相等性,而不是=
.
要输入包含大量空格的AN ENRERE LINE,您可以使用 getline(cin,string_variable);
例如:
string input;
getline(cin, input);
Run Code Online (Sandbox Code Playgroud)
此格式捕获句子中的所有空格,直到return
按下