我强烈建议您将此循环转换为while 循环。但是,无论您是否这样做,以下都是正确的:
只要输入一个EOF,循环就会终止。
EOF 的输入方式取决于您的操作系统(也可能取决于您的终端设置)。在 Linux 上(在默认终端设置下),您会在行首按 Ctrl+D 获得 EOF。在 Windows 上,我认为是 Ctrl+Z。在 Mac 上我不知道。
当然,您也可以将程序的标准输入重定向为来自文件(在这种情况下,EOF ——正如你猜想的那样——在文件末尾生成),或者来自管道(在这种情况下,EOF 生成为编写程序关闭管道后立即)。
如果变量 Ascii 不是 char 或 string 类型,您还可以输入无法解析为该变量数据类型的内容(例如,如果读取 int,除数字之外的任何内容都会导致流报告失败,因此循环终止)。
您可能还想添加另一个结束条件,然后 在循环主体中(在您的 for 循环中当前只是一个空语句)。例如,您可能决定用百分号终止循环;那么你可以写(我仍然假设你没有提供的Ascii的类型是char):
cout << "\nEnter the Sentence now:";
while(cin >> Ascii)
{
cout << "The ascii value of each letter you entered, added to the offset factor is: "
<< (int)Ascii + RandomNumberSubtract << endl);
if (Ascii == '%')
break;
}
但是请注意,通常operator<< 会跳过空格;我猜你不想跳过空格。因此,您可能不应该使用operator<<,而是使用get;这也将允许您使用行尾作为结束条件:
cout << "\nEnter the Sentence now:";
while(std::cin.get(Ascii) && Ascii != '\n')
{
cout << "The ascii value of each letter you entered, added to the offset factor is: "
<< (int)Ascii + RandomNumberSubtract << endl);
}
但是在这种情况下,最好一步读取该行,然后遍历它:
cout << "\nEnter the Sentence now:";
std::string line;
std::getline(std::cin, line);
for (std::string::iterator it = line.begin; it != line.end(); ++it)
{
cout << "The ascii value of each letter you entered, added to the offset factor is: "
<< (int)*it + RandomNumberSubtract << endl;
}
请注意,在 C++11 中,您可以将其简化为
cout << "\nEnter the Sentence now:";
std::string line;
std::getline(std::cin, line);
for (auto ch: line)
{
cout << "The ascii value of each letter you entered, added to the offset factor is: "
<< (int)ch + RandomNumberSubtract << endl;
}