当您在输入cin时输入空格''时,它会将空格前的第一个字符串作为第一个值,将后一个字符串作为下一个值。
所以我们假设我们有这个代码:
cout << "Enter your Name";
cin >> name;
cout << "Enter your age";
cin >> age;
现在,让我们说用户输入“John Bill”。
他的名字是约翰,他的年龄是比尔。
有办法:
让该行自动将其从''更改为'_'?
是否可以将该行读取为该行,并将空格“读作普通字符?”
答案 0 :(得分:4)
用C ++读取一行:
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << "Enter some stuff: " ;
string line;
getline( cin, line );
cout << "You entered: " << line << endl;
}
答案 1 :(得分:2)
你想使用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);
}
}
答案 2 :(得分:0)
当您执行“cin&gt;&gt;”时,您正在使用默认设置的ios :: skipws标志调用cin.get。明确地调用cin.get以使其包含空格。
cin.get(name, strlen(name))
来源: http://minich.com/education/wyo/cplusplus/cplusplusch10/getfunction.htm
答案 3 :(得分:0)
我建议使用std :: string,因为它更安全。 使用char * +通过malloc分配内存是危险的,必须检查分配。但是,您应该查看此链接,了解有关对方何时有用的更多信息https://stackoverflow.com/a/6117751/1669631