为什么它跳出程序?

1 c++

我刚开始学习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();

}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ork 6

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

所以如果你输入:122345<enter>
这一行:

cin.get(s1,19);
Run Code Online (Sandbox Code Playgroud)

将读取12345,但'\n'(通过点击<enter>创建)保留在输入流上.这样下一行就是:

cin.get(s2,9);
Run Code Online (Sandbox Code Playgroud)

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

getch();
Run Code Online (Sandbox Code Playgroud)

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

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

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

因为std :: cin是缓冲流,所以在您按<enter>并刷新流之前,数据不会发送到程序.因此,一次读取一行(通过用户输入)然后独立解析该行通常很有用.这允许您检查最后一个用户输入是否有错误(逐行显示,如果有错误则拒绝).

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.

}
Run Code Online (Sandbox Code Playgroud)

如果你想要先进,那么你也可以查看升压库.它们提供了一些很好的代码,作为一个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.

}
Run Code Online (Sandbox Code Playgroud)