【问题标题】:C optional input on Windows consoleWindows 控制台上的 C 可选输入
【发布时间】:2014-03-31 08:20:22
【问题描述】:

此代码不起作用:

_tprintf(TEXT("Enter password or press enter to skip: "));
pszPassword = new TCHAR[100];
int numFields = _tscanf_s(TEXT("%s"), pszPassword, 100);
if (numFields == 0) // never reached
{
    delete[] pszPassword;
    pszPassword = NULL;
}

按 Enter 不会使 scanf 中止解析输入,因为它会跳过空格,直到找到非空格字符。

我怎样才能实现所需的行为?

该程序实际上是 C 语言,我使用 newdelete 而不是 malloc 但不想使用 std::string 等。

【问题讨论】:

  • 不要对字符串进行 scanf。使用 fgets 等。
  • 有 C 风格的方法吗?

标签: c windows input console scanf


【解决方案1】:

在 C 中使用 fgets 而不是 C++ 中的相同内容,它可以工作:

TCHAR *pszPassword = malloc(100 * sizeof (TCHAR));

_tprintf(TEXT("Enter password or press enter to skip: "));
_fgetts(pszPassword, 100, stdin) ;

if (pszPassword[0] == '\n')
{
  free(pszPassword) ;
  pszPassword = NULL;
}

【讨论】:

    猜你喜欢
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 2014-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    相关资源
    最近更新 更多