cin.Getline什么都不返回

时间:2013-03-27 05:44:35

标签: c++ string cin

我正在努力学习c ++。我现在正在上弦。 我写过这个简单的方法,应该要求输入一个字符串然后返回它。为此我使用cin.getLine()方法,但在使用cin.getLine()之后不会打印字符串

string getString(char string[])
{

  cout << "Please enter a string to process ";
  cin >> string;
  cout << "String in getString before process: " << string << "\n";
  cin.getline(string, STRINGSIZE);
  cout << "String after processing: " << string << "\n"; // here string is not printed
  return string;
}

任何人都可以帮我理解我做错了什么吗?谢谢

1 个答案:

答案 0 :(得分:2)

您首先使用std::stringcin >> string;读取字符串,然后再次阅读cincin.getline(string, STREAMSIZE);的内容 没有必要,请阅读一次并返回:

string getString(char string[]){
  cout << "Please enter a string to process ";
  cin >> string;
  cout << "String in getString before process: " << string << "\n";
  // process this, do whatever you describe as processing it
  cout << "String after processing: " << string << "\n"; // string is printed
  return string;
 }

否则,如果您想使用getline,请执行:

  std::string name;

  std::cout << "Please, enter your full name: ";
  std::getline (std::cin,name); // or std::getline(std::cin,string, 'r'); to read
  //only to delimiter character 'r'
  std::cout << "Hello, " << name << "!\n";

所以要记住的是使用getlinecin,除非确实有某些特殊原因,否则不要同时使用