为什么我的代码的一部分被跳过而不让我输入输入?

问题描述:

为什么我的代码跳过最后一个问题,当我把第一个问题放在很多信息中?我究竟做错了什么?为什么我的代码的一部分被跳过而不让我输入输入?

const int SIZEC =31; 
char phrase[SIZEC]; 
cout << " Provide a phrase, up to 30 characters with spaces. > " << endl; 
cin.getline(phrase, SIZEC); 
cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
cout << " The phrase is: " << phrase << endl; 
cout << endl; 


cout << " Using sring Class Obects " << endl; 
cout << "--------------------------" << endl; 
cout << endl; 

string leter; 
cout << " Provide a single character > " << endl; 
cin >> leter; 
cout << " The single character is: " << leter << endl; 
cout << endl; 

如果之前的代码需要告诉我,我会添加它。

+0

我的老师希望它是一个字符串..:( –

+0

[不要使用'endl'](http://stackoverflow.com/q/213907/995714),除非你知道并且需要它的副作用 –

+0

嗯。什么'副作用'?它只适用于我很好......从来没有一个问题 –

使用std::string::resize作为一种解决方法。

string phrase; 
getline(cin, phrase); 
phrase.resize(30); // phrase will be reduced to 30 chars 

string letter; // better to use char letter 
cin >> letter; 
letter.resize(1); 
+0

请阅读链接第一个是cstring,它必须保持这种方式...我可能应该也添加了这一点当我尝试'phrase.resize (30)'我得到一个错误,我认为这是因为它是一个cstring。 –

的主要问题是,getline在两种情况下表现不同:

  1. 如果至少SIZEC字符被读出,且它们之间不存在换行符(如应该有至少SIZEC+1字节存储数据的读取),它停止读取,并设置所谓的流,这意味着failbit状态位“我没能读的东西,所以输入流可能不正确”。引用cplusplus.com:如果函数提取没有字符,或者如果 分隔字符没有找到一次

    的failbit标志被设置(N-1)个字符都 已经被写入到秒。

  2. 如果遇到换行符,则failbit未设置,并且getline成功读取并忽略换行符。

接下来会发生什么更有趣:提取功能(所有的人,我认为)如果输入流是bad()立即失败(即,无论是failbitbadbit,或eofbit都在流上设置)。特别是,如果先前的提取操作失败,则后续的所有操作都将失败。所以,基本上,如果输入的第一线,不能安装在您的phrase阵列,然后cin变成“坏”和所有进一步的读取操作什么也不做。

您可以通过调用getline这样的后手动复位failbit重写该行为: cin.clear(); 继读操作会成功,直到另一个失败。

你的具体情况,我认为你要读无论长度的第一行,然后第二行。我的话,我想你 应该先检查函数getline是否失败(通过检查cin.failbit()cin.good()),然后要么什么也不做(如果它没有和有阅读额外的换行符没有必要),或重置failbit,而忽略字符,直到第一个换行符。事情是这样的:

#include <iostream> 
#include <limits> 
#include <string> 

using namespace std; 

int main() { 
    char buf[5]; 
    cin.getline(buf, sizeof buf); 
    if (!cin) { // operator ! is overloaded for `istream`, it's equal to `good()` 
     // If stream is bad: first line of the input was truncated, 
     // and following newline character was not read. 

     // Clear failbit so subsequent read operations do something. 
     cin.clear(); 

     // Read remaining of the first line. 
     cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
    } 
    // At this point, first line of the input is consumed 
    // regardless of its length 
    int x; 
    cin >> x; 
    cout << "String: |" << buf << "|\n"; 
    cout << "x: " << x << "\n"; 
} 

你可以阅读更多在计算器上herethere

但是,如果没有理由与istream小号一起使用C风格的字符串,我建议你使用stringstd::getline,而不是(像Shreevardhan's answer);它会产生更清晰的代码,并且不会有额外的情况。

+0

老师想要第一个字符串和第二个字符串。 –