简体   繁体   中英

How to insert white spaces as input into char array with std::cin

I know that I can use:

std::string s; 
std::getline(std::cin,s);

to make white spaces readable in a string how about char arrays?

I think you might use std::cin or std::getline function twice more.

So, if then, you should make std::cin clear. If there are trash values in std::cin , then std::getline might not work.

So, why don't you try this?

std::string s;

std::cout << "Input:";
std::cin.clear()
std::getline(std::cin, s)
std::cout << s << std::endl;

OR

You can also use the member function of std::cin for char array.

char s[1000] = '\0';

std::cout << "Input: ";
std::cin.getline(s, 1000);
std::cout << s << std::endl;

You can use the getline() member of an istream such as std::cin , like this:

char a[80];
std::cin.getline(a, 80);

You can also pass in a 3rd argument which is a delimiter character, and the stream will stop reading when that character is reached.

Here's a demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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