C++ 存储 cin 输入并跳过其他输入

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

}

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

最佳答案

cin 的问题是:

  • ignores the blanks , 换行符 (enter) 为空白
  • 它使用空格作为值的分隔符,因此“Baker street”将被解读为两个字符串,第二个字符串代表城镇。

考虑使用 getline()转换为字符串(最终转换为 stringstream 以进一步解析收到的结果):

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

顺便说一下,streetname 不是整数,对吧? ;-)

关于C++ 存储 cin 输入并跳过其他输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25818289/

相关文章:

c++ - 有人可以向我推荐适用于 x86 和 x86_64 版本操作系统的串行端口通信的 c++ 库吗?

delphi - dll 调用的奇怪字符串行为

javascript - 正则表达式获取两个字符之间的文本?

java - 将从 .txt 文件读取的字符串输入到数组中

java - 如何使用扫描仪获取 boolean 用户输入?

c++ - 在 C++ 中将格式化的数值数据读取到数组

javascript - 编辑textContent或innerHTML会杀死eventListener

c++ - 如何将复杂的指针数据作为属性放入 qt 插件 xml 文件中

c++ - 成员的返回类型中未定义模板占位符,仍然可以正常工作吗?

c++ - 强制转换和 namespace 运算符之间没有空格?