当您在输入 cin 时输入空格 ' ' 时,它将以空格之前的第一个字符串作为第一个值,将后面的字符串作为下一个值。
所以假设我们有这个代码:
cout << "Enter your Name";
cin >> name;
cout << "Enter your age";
cin >> age;
现在,假设用户输入“John Bill”。
他的名字是约翰,他的年龄是比尔。
有没有办法:
该行是否会自动将其从“”更改为“_”?
有没有让它将该行读取为该行并将空格“ ”读取为普通字符?
在 C++ 中读取一行:
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Enter some stuff: " ;
string line;
getline( cin, line );
cout << "You entered: " << line << endl;
}
您想使用可以像这样使用的 cin.getline() :
cin.getline(name, 9999, '\n');
并将包括最多换行符或 9999 个字符的所有内容。不过,这只适用于 c 风格的 char 数组。
getline(cin, name, '\n');
将适用于 std::strings。
如果您想用下划线替换空格,您将不得不手动执行此操作。假设您正在使用 std::string ,您可以创建如下函数:
void replace_space(std::string &theString)
{
std::size_t found = theString.find(" ");
while(found != string::npos)
{
theString[found] = '_';
found = theString.find(" ", found+1);
}
}
当您执行“cin >>”时,您调用 cin.get 时默认设置了 ios::skipws 标志。显式调用 cin.get 使其包含空格。
cin.get(name, strlen(name))
资料来源: http: //minich.com/education/wyo/cplusplus/cplusplusch10/getfunction.htm
我建议使用 std::string 因为它更安全。使用 char * + 通过 malloc 分配内存是危险的,必须检查分配情况。但是,您应该检查此链接以获取有关其他何时有益的更多信息https://stackoverflow.com/a/6117751/1669631