我正在努力学习c ++。我现在正在上弦。 我写过这个简单的方法,应该要求输入一个字符串然后返回它。为此我使用cin.getLine()方法,但在使用cin.getLine()之后不会打印字符串
string getString(char string[])
{
cout << "Please enter a string to process ";
cin >> string;
cout << "String in getString before process: " << string << "\n";
cin.getline(string, STRINGSIZE);
cout << "String after processing: " << string << "\n"; // here string is not printed
return string;
}
任何人都可以帮我理解我做错了什么吗?谢谢
答案 0 :(得分:2)
您首先使用std::string
向cin >> string;
读取字符串,然后再次阅读cin
中cin.getline(string, STREAMSIZE);
的内容
没有必要,请阅读一次并返回:
string getString(char string[]){
cout << "Please enter a string to process ";
cin >> string;
cout << "String in getString before process: " << string << "\n";
// process this, do whatever you describe as processing it
cout << "String after processing: " << string << "\n"; // string is printed
return string;
}
否则,如果您想使用getline
,请执行:
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name); // or std::getline(std::cin,string, 'r'); to read
//only to delimiter character 'r'
std::cout << "Hello, " << name << "!\n";
所以要记住的是使用getline
或cin
,除非确实有某些特殊原因,否则不要同时使用