简体   繁体   English

命令提示符关闭而不接受输入

[英]Command prompt closes without taking input

Why am I not being able to enter anything? 为什么我无法输入任何东西? The program on running doesn't wait for my input and the cmd prints Enter a Filename and closes. 运行程序不等待我的输入,cmd打印Enter a Filename并关闭。 I am executing it on Visual Studio 2008. 我在Visual Studio 2008上执行它。

int main(int argc, char* argv[])
    {
        if(argc<2)
            printf("\nEnter a filename");
        else
        { 
            //code
        }
        getch();
        return 0;
        }

What am I doing wrong? 我究竟做错了什么?

I'm guessing something is in the buffer. 我猜是在缓冲区里有什么东西。 Try seeing what it is? 试试看它是什么?

int main(int argc, char* argv[])
{
    if(argc<2)
        printf("\nEnter a filename");
    else
    { 
        //code
    }

    while (true)
    {
        int c;
        c = getch();
        printf( ": %d\n", c );
    }
    return 0;
 }

After your response it appears there is the letter b in your input stream when your program is called. 在您的响应之后,当您的程序被调用时,输入流中会出现字母b。 Not sure how to explain that. 不知道如何解释。 Are you trying to get a whole string and not just a character? 你想要获得整个字符串而不只是一个字符?

int main(int argc, char* argv[])
{
    char string [256];
    if(argc<2)
    {
        printf("Enter a filename:");
        gets (string);
    }
    else
    { 
        //assign string to argv[1]
    }


   printf ("Your filename is: %s\n",string);
   return 0;
  }

You should usually end, not start, the outputted string with newline (because on stdout a newline may flush buffers). 您通常应该以换行结束输出字符串,而不是以新行开头(因为在stdout ,换行符可能会刷新缓冲区)。 Or you should call fflush(stdout); 或者你应该叫fflush(stdout); before your call to getch() . 在你打电话给getch() So try with printf("Enter a filename:\\n"); 所以尝试使用printf("Enter a filename:\\n");

Try running your program without debugging ( Ctrl+F5 in Visual Studio). 尝试运行程序而不进行调试(在Visual Studio中为Ctrl+F5 )。 This will keep the cmd window open after the program has finished. 这将在程序完成后保持cmd窗口打开。

(edit)Perhaps you want to do something like this: (编辑)也许你想做这样的事情:

int main(int argc, char* argv[])
    {
        string filename;
        if(argc<2)
        {
            printf("\nEnter a filename");
            cin >> filename;
        }
        else
        { 
            //code
        }
        // getch(); // Use Ctrl+F5 instead
        return 0;
    }

getch() only gets 1 char from input stream. getch()只从输入流中获取1个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM