我在跳过某些输入时遇到了麻烦。
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); }
}
如果用户只点击输入,我的所有尝试都无法跳过输入。
答案 0 :(得分:1)
代码cin
的问题是:
考虑在字符串中使用getline()
(最后使用stringstream来进一步解析收到的结果):
getline (cin, input); // instead of cin>>input;
顺便说一下,streetname不是一个整数,是吗? ; - )