C ++值更新/忽略

时间:2014-09-13 04:42:16

标签: c++ parameter-passing cin getline

所以我有这个

int main(){
  string input;
  string lastName;
  string firstName;
  int age;
  int streetNum;
  string streetName;
  string town;
  string zipCode;
  float balance;
  Update(lastName, firstName, age, streetNum, streetName, town, zipCode, balance);
}

这是功能Update

void Update(string &lastname, string &firstname, int &age, int &streetnum, string &streetname, string &town, string &zipcode, float &balance){
  cout << "Update the following, enter nothing to leave the same: " << endl;
  string input;

  cout << "Last name: ";
  getline(cin, input);
  if (input != "\n") { lastname = input; }

  cout << "First name: ";
  getline(cin, input);
  if (input != "\n") { firstname = input; }

  cout << "Age: ";
  getline(cin, input);
  if (input != "\n") { age = atoi(input.c_str()); }

  cout << "Street number: ";
  getline(cin, input);
  if (input != "\n") { streetnum = atoi(input.c_str()); }

  cout << "Street name: ";
  getline(cin, input);
  if (input != "\n") { streetname = input; }

  cout << "Town name:";
  getline(cin, input);
  if (input != "\n") { town = input; }

  cout << "ZipCode: ";
  getline(cin, input);
  if (input != "\n") { zipcode = input; }

  cout << "Balance: ";
  getline(cin, input);
  if (input != "\n") { balance = atof(input.c_str()); }

}

如果输入为'\ n',我的目标是更新值或跳到下一个值。

一旦运行并且程序调用Update,它会在同一行打印出“Last Name:First Name:”,而不会让用户在lastname中输入任何内容。我不知道为什么会这样做。任何提示或线索都会有所帮助。

1 个答案:

答案 0 :(得分:0)

getline()不等待用户输入。我相信除非你被告知使用getline(),否则你可能想要使用cin。看起来如此:

cout<< "Lastname: ";
cin>>input;
if(input != " ")
{
    lastname= input;
}

我预见到的唯一问题是你不能使用'\ n'作为你的if语句的条件。在上面的例子中,我使用了一个空格作为我的跳过字符。