gpt4 book ai didi

c++ - 为什么会跳出程序?

转载 作者:行者123 更新时间:2023-11-30 00:41:07 24 4
gpt4 key购买 nike

我刚开始学习 C++。

当我执行我的代码时,它会毫无错误地跳出程序。为什么?

#include "stdafx.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{

char s1[20],s2[10];
cout<<" enter a number : ";
cin.get(s1,19);
cout<<" enter a number : ";
cin.get(s2,9);

cout<<s1<<"/n"<<s2;

getch();

}

最佳答案

方法 get() 读取到 '\n' 字符但不提取它。

因此,如果您键入:122345<enter>
这一行:

cin.get(s1,19);

将阅读12345 ,但“\n”(通过按 创建)留在输入流中。因此,下一行要阅读:

cin.get(s2,9);

当它看到 '\n' 并停止时,不会读取任何内容。但它也不会提取 '\n'。所以输入流仍然有'\n'。所以这一行:

getch();

只是从输入流中读取 '\n' 字符。然后允许它完成处理并正常退出程序。

好的。这就是正在发生的事情。但还有更多。您不应该使用 get() 来读取格式化输入。使用运算符 >> 将格式化数据读入正确的类型。

int main()
{
int x;
std::cin >> x; // Reads a number into x
// error if the input stream does not contain a number.
}

因为 std::cin 是缓冲流,所以数据不会发送到程序,直到您按下 并且流被刷新。因此,一次读取文本(从用户输入)一行然后独立解析该行通常很有用。这使您可以检查最后的用户输入是否有错误(逐行检查,如果有错误则拒绝输入)。

int main()
{
bool inputGood = false;
do
{
std::string line;
std::getline(std::cin, line); // Read a user line (throws away the '\n')

std::stringstream data(line);
int x;
data >> x; // Reads an integer from your line.
// If the input is not a number then data is set
// into error mode (note the std::cin as in example
// one above).
inputGood = data.good();
}
while(!inputGood); // Force user to do input again if there was an error.

}

如果你想更进一步,那么你也可以看看 boost 库。它们通常提供了一些不错的代码,作为 C++ 程序,您应该了解 boost 的内容。但我们可以将上面的代码重写为:

int main()
{
bool inputGood = false;
do
{
try
{
std::string line;
std::getline(std::cin, line); // Read a user line (throws away the '\n')

int x = boost::lexical_cast<int>(line);
inputGood = true; // If we get here then lexical_cast worked.
}
catch(...) { /* Throw away the lexical_cast exception. Thus forcing a loop */ }
}
while(!inputGood); // Force user to do input again if there was an error.

}

关于c++ - 为什么会跳出程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4346852/

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