检查时感到困惑
Confused about while check
我对这段代码感到困惑:
#include "stdafx.h"
#include "std_lib_facilities.h"
int main()
{
string name_one;
string name_two;
string name_three;
cout << "Please enter a name: ";
cin >> name_one;
cout << "\nReading data...";
while (name_one.empty())
{
cout << "\nFailed!";
cout << "Please enter a name: ";
cin >> name_one;
cout << "\nReading data...";
}
cout << "Completed!\n";
keep_window_open();
return 0;
}
这很容易,但是当我调试它时,例如我什么都不写,只是按回车键,它什么也没做。只是一直在该行下方显示一个闪烁的下划线,如果我一直按 Enter,它只会逐行跳转。为什么程序不读取条件?我想要的是,如果用户不写任何东西,while
中的条件开始!
您正在使用流提取器 >>
,这是一个 格式化输入函数。 对于许多类型(例如基本类型和 std::string
),它们首先跳过流中当前的所有空白(1),然后提取字符,只要它们是您要提取的数据类型的有效表示即可。
换句话说,当你在标准输入上按Enter时,流中只会有一个换行符。换行符是空格,所以 >>
函数仍然卡在它的 "skip starting whitespace" 模式中。只有当您输入非空白字符时,第二部分 ("extract characters and try to interpret them as a representation of the extracted type") 才会开始。
如果你想总是按行阅读,你可以使用getline
stream function, or the std::getline
function. You can also combine these with an istringstream
对象来解析行。
(1) 此行为可由流操纵器控制 skipws
and noskipws
, or directly by the stream's formatting flags.
我对这段代码感到困惑:
#include "stdafx.h"
#include "std_lib_facilities.h"
int main()
{
string name_one;
string name_two;
string name_three;
cout << "Please enter a name: ";
cin >> name_one;
cout << "\nReading data...";
while (name_one.empty())
{
cout << "\nFailed!";
cout << "Please enter a name: ";
cin >> name_one;
cout << "\nReading data...";
}
cout << "Completed!\n";
keep_window_open();
return 0;
}
这很容易,但是当我调试它时,例如我什么都不写,只是按回车键,它什么也没做。只是一直在该行下方显示一个闪烁的下划线,如果我一直按 Enter,它只会逐行跳转。为什么程序不读取条件?我想要的是,如果用户不写任何东西,while
中的条件开始!
您正在使用流提取器 >>
,这是一个 格式化输入函数。 对于许多类型(例如基本类型和 std::string
),它们首先跳过流中当前的所有空白(1),然后提取字符,只要它们是您要提取的数据类型的有效表示即可。
换句话说,当你在标准输入上按Enter时,流中只会有一个换行符。换行符是空格,所以 >>
函数仍然卡在它的 "skip starting whitespace" 模式中。只有当您输入非空白字符时,第二部分 ("extract characters and try to interpret them as a representation of the extracted type") 才会开始。
如果你想总是按行阅读,你可以使用getline
stream function, or the std::getline
function. You can also combine these with an istringstream
对象来解析行。
(1) 此行为可由流操纵器控制 skipws
and noskipws
, or directly by the stream's formatting flags.