【问题标题】:cin.getline() skipscin.getline() 跳过
【发布时间】:2012-09-13 08:26:53
【问题描述】:

好的,这是一个非常简单的问题: 在以下代码部分中,“cin.getline()”没有运行:

cout<< "Specify USB drive letter: ";
char usbD[1];
char outputLoc [40];
cin.getline(usbD, 1, '\n');
cout<< "\n" << usbD << "\n";

我做错了什么?

【问题讨论】:

  • 为什么不只是char usbD; std::cin &gt;&gt; usbD;
  • 始终在您尝试读取某些内容后检查读取操作的结果。您会注意到 std::cin.getline() 实际上 is 运行但失败了。

标签: c++ getline cin


【解决方案1】:

您需要 2 个空格来存储单个字符的字符串,这是因为 c++ 使用 \0 来分隔字符串。您可以按如下方式更改代码:

cout<< "Specify USB drive letter: ";
char usbD[2];
char outputLoc [40];
cin.getline(usbD, 2, '\n'); // the 2 here will be the drive letter and the ending \0
cout<< "\n" << usbD << "\n";

【讨论】:

  • 对,我忘了为终止字符添加空格,感谢您的帮助:)
【解决方案2】:

您需要 usbD[2] - 用于字符串 '\0' 的字母和结尾。

来自http://www.cplusplus.com/reference/iostream/istream/getline/

  • istream& getline (char* s, streamsize n);
  • istream& getline (char* s, streamsize n, char delim );
s
    A pointer to an array of characters where the string is stored as a c-string.

n
    Maximum number of characters to store (including the terminating null character).

【讨论】:

    【解决方案3】:

    @PiotrNycz 是对的,您没有为终止空值留出空间。但如果你只想要一个字符,就没有理由使用数组。

    char usbD;
    cin.get(usbD);
    

    【讨论】:

      猜你喜欢
      • 2015-03-24
      • 2013-10-03
      • 1970-01-01
      • 2012-04-29
      • 2011-04-23
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      • 2011-06-12
      相关资源
      最近更新 更多