2012-02-11 34 views
0

我在尝试学习C++,一个练习是构建一个命令行工具,该工具接受用户输入并将其存储在char数组中,直到用户输入空行。我认为我的骷髅是正确的,但无论出于何种原因,我的这段时间都在持续。我的代码如下:针对 n的C++测试 n

char a[256]; 

    //while the first character isn't a new line 
    while (a[0] != '\n') { 

     //get the char array 
     cin >> a; 

     cout << a; 

    } 

任何帮助将不胜感激。

+9

如果你真的想学习C++,请放下你正在使用的任何教程,并购买一本教你如何正确使用字符串的书(http:// jcatki。 no-ip.org/fncpp/Resources)。 – 2012-02-11 15:43:45

回答

3

您无法使用operator>>检测换行符。对于大多数类型,它使用空格作为分隔符,并且不区分空格,制表符或换行符。使用getline来代替:

for (std::string line; std::getline(std::cin, line);) 
{ 
    if (line.empty()) 
    { 
     // if the line is empty, that means the user didn't 
     // press anything before hitting the enter key 
    } 
} 
1

初学者:使用std :: string而不是char数组并选择有用的变量名称。

#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 
    for(string text;getline(cin, text);) { 
     if (!text.empty()) { 
      cout << text << endl; 
     } else { 
      break; 
     }  
    } 
} 
+1

测试你的代码。 http://ideone.com/wDFGw – 2012-02-11 16:16:03

+0

谢谢Benjamin,我不知道ideone.com - http://ideone.com/Z95Ef – 2012-02-11 17:15:00

+0

好吧,现在看看你的输出。它不会停留在空行上,就像OP所要求的那样。 – 2012-02-11 17:27:03