C ++存储cin输入和跳过其他人

时间:2014-09-12 23:24:56

标签: c++ string input cin

我在跳过某些输入时遇到了麻烦。

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);
}

这个想法是,如果用户什么都没有输入(只是点击输入),那么该值应该保持不变并移动到下一个输入。

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;
  size_t sz;

  cout << "Last name: ";
  cin >> input;
  if (!input.empty()) { lastname = input; }

  cout << "First name: ";
  cin >> input;
  if (!input.empty()) { firstname = input; }

  cout << "Age: ";
  cin >> input;
  if (!input.empty()) { age = stoi(input, &sz); }

  cout << "Street number: ";
  cin >> input;
  if (!input.empty()) { streetnum = stoi(input, &sz); }

  cout << "Street name: ";
  cin >> input;
  if (!input.empty()) { streetname = stoi(input); }

  cout << "Town name:";
  cin >> input;
  if (!input.empty()) { town = input; }

  cout << "ZipCode: ";
  cin >> input;
  if (!input.empty()) { zipcode = input; }

  cout << "Balance: ";
  cin >> input;
  if (!input.empty()) { balance = stof(input); }

}

如果用户只点击输入,我的所有尝试都无法跳过输入。

1 个答案:

答案 0 :(得分:1)

代码cin的问题是:

  • ignores the blanks,换行符(输入)为空白
  • 它使用空白作为价值的分隔符,因此&#34; Baker street&#34;将被视为两个字符串,第二个字符串用于该镇。

考虑在字符串中使用getline()(最后使用stringstream来进一步解析收到的结果):

   getline (cin, input);    // instead of cin>>input;

顺便说一下,streetname不是一个整数,是吗? ; - )