读取数据时std :: ws(空格)的作用 [英] The role of std::ws (whitespace) when reading data
问题描述
保存在我的文件中的数据是(为此测试故意在开头和结尾处添加了空格):
Data saved in my file is (white spaces added at both beginning and end on purpose for this test):
1 2 3
使用以下带有或不带有"std :: ws"代码的代码加载数据不会造成任何差异.因此,我对"std :: ws"的角色感到困惑,因为我看到了使用它的代码.有人可以解释一下吗?谢谢!
Loading the data using the code below with or without "std::ws" does not cause any difference. So I am confused by the role of "std::ws" as I have seen code using it. Can someone explain a little bit? Thanks!
void main ()
{
ifstream inf;
inf.open ("test.txt");
double x=0, y=0, z=0;
string line;
getline(inf, line);
istringstream iss(line);
//Using "std::ws" here does NOT cause any difference
if (!(iss >> std::ws >> x >> y >> z >> std::ws))
{
cout << "Format error in the line" << endl;
}
else
{
cout << x << y << z << endl;
}
iss.str(std::string ());
iss.clear();
cin.get();
}
推荐答案
std::ws
的主要用途是在格式化和未格式化的输入之间切换:
The primary use of std::ws
is when switching between formatted and unformatted input:
- 格式化的输入,即通常使用`in >>值的输入运算符,跳过前导空格并在填充格式时停止
- 未格式化的输入,例如
std::getline(in, value)
不会不跳过前导空格
- formatted input, i.e., the usual input operators using `in >> value, skip leading whitespace and stop whenever the format is filled
- unformatted input, e.g.,
std::getline(in, value)
does not skip leading whitespace
例如,当读取age
和fullname
时,您可能会想像这样读取它:
For example, when reading an age
and a fullname
you might be tempted to read it like this:
int age(0);
std::string fullname;
if (std::cin >> age && std::getline(std::cin, fullname)) { // BEWARE: this is NOT a Good Idea!
std::cout << "age=" << age << " fullname='" << fullname << "'\n";
}
但是,如果我使用以下信息输入
However, if I'd enter this information using
47
Dietmar Kühl
它将打印出这样的内容
age=47 fullname=''
问题在于,47
之后的换行符仍然存在,并立即填充std::getine()
请求.因此,您宁愿使用此语句来读取数据
The problem is that the newline following the 47
is still present and immediately fills the std::getine()
request. As a result you'd rather use this statement to read the data
if (std::cin >> age && std::getline(std::cin >> std::ws, fullname)) {
...
}
使用std::cin >> std::ws
会跳过空格,尤其是换行符,并在输入实际内容的地方继续阅读.
The use of std::cin >> std::ws
skips the whitespace, in particular the newline, and carries on reading where the actual content is entered.
这篇关于读取数据时std :: ws(空格)的作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!