简体   繁体   English

C++,用户将字母、数字和空格输入到字符串中

[英]C++, User input of letters, numbers, and spaces into a string

So I have a small problem and I can't find an elegant solution to it.所以我有一个小问题,我找不到优雅的解决方案。

I'm asking the user to input their address.我要求用户输入他们的地址。 How would I put that into a string?我如何将其放入字符串中? It would contain letters, numbers, and spaces.它将包含字母、数字和空格。 I tried the getline function but no success with that.我尝试了 getline 函数,但没有成功。

cout << "\nEnter customer street address" << endl; cout << "\n请输入客户街道地址" << endl;
cin >> address;辛>>地址;

To do something like that you'll want to use a string and getline . 要执行类似的操作,您将需要使用stringgetline

string address;
cout << "\nEnter customer street address: ";
cin.ignore(numeric_limits<streamsize>::max()); // May or may not be needed.
getline(cin, address);

string Reference 字符串参考
getline Reference numeric_limits Reference getline参考 numeric_limits参考

you can use std::getline 您可以使用std :: getline

int main()
{
    // greet the user
    std::string name;
    std::cout << "What is your name? ";
    std::getline(std::cin, name);
    std::cout << "Hello " << name << ", nice to meet you.\n";
}

Like said: 就像说:

  string address;
  cout << "\nEnter customer street address: ";
  getline(cin, address);

With this your input can be typed until user hits enter (newline); 这样,您可以输入您的输入内容,直到用户点击回车(换行符)为止。

If you want multiple line input you'll still need some stop criteria. 如果要多行输入,则仍然需要一些停止条件。

You should use getLine like that:你应该像这样使用 getLine :

string address;
cout << "\nEnter customer street address: ";
cin.getLine(address,MaxLengthOfAddress,\n);

https://www.geeksforgeeks.org/getline-string-c/ https://www.geeksforgeeks.org/getline-string-c/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM